Sample code for 30+ languages & platforms
Swift

Delete All IMAP Email

Demonstrates two ways to delete all email in a mailbox on an IMAP server.

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()!

    // Turn on session logging:
    imap.keepSessionLog = true

    // Connect to an 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.RubyMail")
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    // Get the complete set of Uids for email in the selected mailbox.
    let messageSet = CkoMessageSet()!
    success = imap.queryMbx(criteria: "ALL", bUid: true, msgSet: messageSet)
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    // Set the Deleted flag for each message.
    // (ExpungeAndClose must be called to finalize the delete.)
    success = imap.setFlags(messageSet: messageSet, flagName: "Deleted", value: 1)
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    // Alternatively, the Deleted flag may be set for each UID
    // individiually, but this is less efficient:
    var i: Int = 0
    var n: Int = messageSet.count.intValue
    while i < n {
        success = imap.setFlag(msgId: messageSet.getId(index: i), bUid: messageSet.hasUids, flagName: "Deleted", value: 1)
        if success == false {
            print("\(imap.lastErrorText!)")
            return
        }

        i = i + 1
    }

    // Expunge and close the mailbox.
    success = imap.expungeAndClose()
    if success == false {
        print("\(imap.lastErrorText!)")
        return
    }

    // Display the session log.
    print("\(imap.sessionLog!)")

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

}