Sample code for 30+ languages & platforms
Python 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 Python Downloads

Python
import sys
import chilkat2

success = False

# Assumes Chilkat is unlocked. See Global Unlock Sample.

imap = chilkat2.Imap()
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.PeekMode = True
imap.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 = chilkat2.MessageSet()
success = imap.QueryMbx("SUBJECT \"Sample message\"",True,matches)
if (success != True):
    print(imap.LastErrorText)
    sys.exit()

if (matches.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 = chilkat2.Email()
success = imap.FetchEmail(False,uid,True,email)
if (success != True):
    print(imap.LastErrorText)
    sys.exit()

print("Mailbox INBOX, UIDVALIDITY " + str(imap.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.NumAttachments))

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

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