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

Lua
local chilkat = require("chilkat")

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

local imap = chilkat.Imap.new()
imap.ssl = true
imap.port = 993
imap.require_ssl_cert_verify = true
imap.peek_mode = true
imap.auto_download_attachments = true
local success = imap:connect("imap.example.com")
if not success then
    print(imap.last_error_text)
    return
end

success = imap:login("MAIL_USER", "MAIL_PASSWORD")
if not success then
    print(imap.last_error_text)
    return
end

success = imap:select_mailbox("INBOX")
if not success then
    print(imap.last_error_text)
    return
end

local matches = chilkat.MessageSet.new()
success = imap:query_mbx("SUBJECT \"Sample message\"", true, matches)
if not success then
    print(imap.last_error_text)
    return
end

if matches.count == 0 then
    print("No matching message in INBOX.")
    success = imap:disconnect()
    if not success then
        print(imap.last_error_text)
        return
    end

    return
end

-- The search returned UIDs. Use the same identifier type for the fetch.
local uid = matches:get_id(0)
local email = chilkat.Email.new()
success = imap:fetch_email(false, uid, true, email)
if not success then
    print(imap.last_error_text)
    return
end

print("Mailbox INBOX, UIDVALIDITY " .. imap.uid_validity .. ", UID " .. uid)
success = imap:disconnect()
if not success then
    print(imap.last_error_text)
    return
end

-- The downloaded Email remains usable after disconnecting.
print("Subject: " .. email.subject .. "  Files: " .. email.num_attachments)

success = email:save_eml("imap-received.eml")
if not success then
    print(email.last_error_text)
    return
end

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