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

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

imap = Chilkat::CkImap.new()
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() + "\n";
    exit
end

success = imap.Login("MAIL_USER","MAIL_PASSWORD")
if (success != true)
    print imap.lastErrorText() + "\n";
    exit
end

success = imap.SelectMailbox("INBOX")
if (success != true)
    print imap.lastErrorText() + "\n";
    exit
end

matches = Chilkat::CkMessageSet.new()
success = imap.QueryMbx("SUBJECT \"Sample message\"",true,matches)
if (success != true)
    print imap.lastErrorText() + "\n";
    exit
end

if (matches.get_Count() == 0)
    print "No matching message in INBOX." + "\n";
    success = imap.Disconnect()
    if (success != true)
        print imap.lastErrorText() + "\n";
        exit
    end

    exit
end

#  The search returned UIDs. Use the same identifier type for the fetch.
uid = matches.GetId(0)
email = Chilkat::CkEmail.new()
success = imap.FetchEmail(false,uid,true,email)
if (success != true)
    print imap.lastErrorText() + "\n";
    exit
end

print "Mailbox INBOX, UIDVALIDITY " + imap.get_UidValidity().to_s() + ", UID " + uid.to_s() + "\n";
success = imap.Disconnect()
if (success != true)
    print imap.lastErrorText() + "\n";
    exit
end

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

success = email.SaveEml("imap-received.eml")
if (success != true)
    print email.lastErrorText() + "\n";
    exit
end

print "Saved imap-received.eml." + "\n";