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

Xbase++
LOCAL nSuccess
LOCAL oImap
LOCAL oMatches
LOCAL nUid
LOCAL oEmail

nSuccess := 0

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

oImap := CreateObject("Chilkat.Imap")
oImap:Ssl := 1
oImap:Port := 993
oImap:RequireSslCertVerify := 1
oImap:PeekMode := 1
oImap:AutoDownloadAttachments := 1
nSuccess := oImap:Connect("imap.example.com")
IF (nSuccess != 1)
    ? oImap:LastErrorText
    oImap:destroy()
    RETURN
ENDIF

nSuccess := oImap:Login("MAIL_USER", "MAIL_PASSWORD")
IF (nSuccess != 1)
    ? oImap:LastErrorText
    oImap:destroy()
    RETURN
ENDIF

nSuccess := oImap:SelectMailbox("INBOX")
IF (nSuccess != 1)
    ? oImap:LastErrorText
    oImap:destroy()
    RETURN
ENDIF

oMatches := CreateObject("Chilkat.MessageSet")
nSuccess := oImap:QueryMbx('SUBJECT "Sample message"', 1, oMatches)
IF (nSuccess != 1)
    ? oImap:LastErrorText
    oImap:destroy()
    oMatches:destroy()
    RETURN
ENDIF

IF (oMatches:Count == 0)
    ? "No matching message in INBOX."
    nSuccess := oImap:Disconnect()
    IF (nSuccess != 1)
        ? oImap:LastErrorText
        oImap:destroy()
        oMatches:destroy()
        RETURN
    ENDIF

    oImap:destroy()
    oMatches:destroy()
    RETURN
ENDIF

//  The search returned UIDs. Use the same identifier type for the fetch.
nUid := oMatches:GetId(0)
oEmail := CreateObject("Chilkat.Email")
nSuccess := oImap:FetchEmail(0, nUid, 1, oEmail)
IF (nSuccess != 1)
    ? oImap:LastErrorText
    oImap:destroy()
    oMatches:destroy()
    oEmail:destroy()
    RETURN
ENDIF

? "Mailbox INBOX, UIDVALIDITY " + Str(oImap:UidValidity) + ", UID " + Str(nUid)
nSuccess := oImap:Disconnect()
IF (nSuccess != 1)
    ? oImap:LastErrorText
    oImap:destroy()
    oMatches:destroy()
    oEmail:destroy()
    RETURN
ENDIF

//  The downloaded Email remains usable after disconnecting.
? "Subject: " + oEmail:Subject + "  Files: " + Str(oEmail:NumAttachments)

nSuccess := oEmail:SaveEml("imap-received.eml")
IF (nSuccess != 1)
    ? oEmail:LastErrorText
    oImap:destroy()
    oMatches:destroy()
    oEmail:destroy()
    RETURN
ENDIF

? "Saved imap-received.eml."

oImap:destroy()
oMatches:destroy()
oEmail:destroy()