Swift Requires Chilkat v11.0.0+
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
let imap = CkoImap()!
imap.ssl = true
imap.port = 993
imap.requireSslCertVerify = true
imap.peekMode = true
imap.autoDownloadAttachments = true
success = imap.connect(hostname: "imap.example.com")
if success != true {
print("\(imap.lastErrorText!)")
return
}
success = imap.login(login: "MAIL_USER", password: "MAIL_PASSWORD")
if success != true {
print("\(imap.lastErrorText!)")
return
}
success = imap.selectMailbox(mailbox: "INBOX")
if success != true {
print("\(imap.lastErrorText!)")
return
}
let matches = CkoMessageSet()!
success = imap.queryMbx(criteria: "SUBJECT \"Sample message\"", bUid: true, msgSet: matches)
if success != true {
print("\(imap.lastErrorText!)")
return
}
if matches.count.intValue == 0 {
print("No matching message in INBOX.")
success = imap.disconnect()
if success != true {
print("\(imap.lastErrorText!)")
return
}
return
}
// The search returned UIDs. Use the same identifier type for the fetch.
var uid: UInt32 = matches.getId(index: 0)
let email = CkoEmail()!
success = imap.fetchEmail(headerOnly: false, msgId: uid, bUid: true, email: email)
if success != true {
print("\(imap.lastErrorText!)")
return
}
print("Mailbox INBOX, UIDVALIDITY \(imap.uidValidity), UID \(uid)")
success = imap.disconnect()
if success != true {
print("\(imap.lastErrorText!)")
return
}
// The downloaded Email remains usable after disconnecting.
print("Subject: \(email.subject!) Files: \(email.numAttachments.intValue)")
success = email.saveEml(path: "imap-received.eml")
if success != true {
print("\(email.lastErrorText!)")
return
}
print("Saved imap-received.eml.")
}