Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

Sorting Email

Demonstrates how to sort an email bundle.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    let imap = CkoImap()!

    //  Connect to the IMAP server.
    //  Use TLS
    imap.ssl = true
    imap.port = 993
    success = imap.connect(hostname: "imap.example.com")
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    //  Login
    success = imap.login(login: "myLogin", password: "myPassword")
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    //  Select an IMAP mailbox
    success = imap.selectMailbox(mailbox: "Inbox")
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    var fetchUids: Bool = true
    let messageSet = CkoMessageSet()!
    success = imap.queryMbx(criteria: "ALL", bUid: fetchUids, msgSet: messageSet)
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    //  Fetch the email headers into a bundle object:
    let bundle = CkoEmailBundle()!
    var headersOnly: Bool = true
    success = imap.fetchMsgSet(headersOnly: headersOnly, msgSet: messageSet, bundle: bundle)
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    //  Sort the email bundle by date, recipient, sender, or subject:
    var ascending: Bool = true
    bundle.sort(byDate: ascending)

    //  To sort by recipient, sender, or subject, call 
    //  SortBySender, SortByRecipient, or SortBySubject.

    //  Display the Subject and From of each email.
    let email = CkoEmail()!
    var i: Int = 0
    while i < bundle.messageCount.intValue {
        bundle.email(at: i, email: email)

        print("\(email.getHeaderField(fieldName: "Date")!)")
        print("\(email.subject!)")
        print("\(email.from!)")
        print("--")

        i = i + 1
    }

    //  Disconnect from the IMAP server.
    success = imap.disconnect()

}