Sample code for 30+ languages & platforms
CkPython Requires Chilkat v11.0.0+

Find an email by subject and fetch it by IMAP UID

See more Email Object Examples

Search the selected INBOX by subject and fetch the first matching UID into an Email. The example requests complete attachment bodies and uses peek mode to preserve the read flag. Configure your own IMAP TLS endpoint and credentials.

Chilkat CkPython Downloads

CkPython
import sys
import chilkat

success = False

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

imap = chilkat.CkImap()
imap.put_Ssl(True)
imap.put_Port(993)
imap.put_RequireSslCertVerify(True)
imap.put_PeekMode(True)
imap.put_AutoDownloadAttachments(True)
success = imap.Connect("imap.example.com")
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

success = imap.Login("MAIL_USER","MAIL_PASSWORD")
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

success = imap.SelectMailbox("INBOX")
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

matches = chilkat.CkMessageSet()
success = imap.QueryMbx("SUBJECT \"Sample message\"",True,matches)
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

if (matches.get_Count() == 0):
    print("No matching message in INBOX.")
    success = imap.Disconnect()
    if (success != True):
        print(imap.lastErrorText())
        sys.exit()

    sys.exit()

#  The search returned UIDs. Use the same identifier type for the fetch.
uid = matches.GetId(0)
email = chilkat.CkEmail()
success = imap.FetchEmail(False,uid,True,email)
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

print("Mailbox INBOX, UIDVALIDITY " + str(imap.get_UidValidity()) + ", UID " + str(uid))
success = imap.Disconnect()
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

#  The downloaded Email remains usable after disconnecting.
print("Subject: " + email.subject() + "  Files: " + str(email.get_NumAttachments()))

success = email.SaveEml("imap-received.eml")
if (success != True):
    print(email.lastErrorText())
    sys.exit()

print("Saved imap-received.eml.")