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

Gmail IMAP: Identify Messages and Threads Across Folders

See more GMail SMTP/IMAP/POP Examples

Sample INBOX and the discovered All Mail folder, fetch Gmail message and thread IDs, and deduplicate messages appearing in both. Each X-GM-MSGID maps to an X-GM-THRID; equal thread IDs group messages in a Gmail conversation.

All identifiers are strings. IMAP UIDs identify messages only within one mailbox and UIDVALIDITY. Gmail IDs identify messages across labels, while the RFC Message-ID header is a separate identifier. Gmail IMAP IDs are unsigned decimal values; Gmail REST uses the corresponding hexadecimal strings. Do not pass these decimal strings directly as REST IDs.

The example reads at most ten messages per folder. Its regular expression extracts only the requested numeric metadata from a single-line FETCH result, tolerating attribute order and unrelated notifications. It is not a general IMAP/MIME parser. A vanished message is skipped. No message body is downloaded or marked read.

Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.

Google documentation

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    let statusText = CkoStringBuilder()!
    let statusMatch = CkoJsonObject()!
    var completed: Int
    let token = CkoJsonObject()!
    success = token.loadFile(path: "gmail-mail-token.json")
    if success != true {
        print("Could not load the protocol token from the private working directory.")
        return
    }

    if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
        print("Authorize or refresh the mailbox first.")
        return
    }

    var mailbox: String? = "user@example.com"
    let imap = CkoImap()!
    imap.ssl = true
    imap.port = 993
    imap.requireSslCertVerify = true
    imap.authMethod = "XOAUTH2"
    success = imap.connect(hostname: "imap.gmail.com")
    if success != true {
        print("Could not establish the Gmail IMAP TLS connection.")
        return
    }

    success = imap.login(login: mailbox, password: token.string(of: "access_token"))
    if success != true {
        imap.disconnect()
        print("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
        return
    }

    var capabilities: String? = imap.capability()
    if (imap.lastMethodSuccess != true) || (imap.hasCapability(name: "X-GM-EXT-1", capabilityResponse: capabilities) != true) {
        imap.logout()
        imap.disconnect()
        print("Gmail IMAP extensions are unavailable.")
        return
    }

    let folders = CkoMailboxes()!
    success = imap.mbxList(subscribed: false, reference: "", mbxPattern: "*", mboxes: folders)
    if success != true {
        imap.logout()
        imap.disconnect()
        print("Could not list Gmail folders.")
        return
    }

    var allMail: String? = ""
    var folderMatches: Int = 0
    var f: Int = 0
    while (f < folders.count.intValue) {
        if (folders.hasFlag(index: f, flagName: "\\All") == true) && (folders.isSelectable(index: f) == true) {
            allMail = folders.getName(index: f)
            folderMatches = folderMatches + 1
        }

        f = f + 1
    }

    if folderMatches != 1 {
        imap.logout()
        imap.disconnect()
        print("Expected one selectable folder with the \\All special-use attribute. Check label visibility.")
        return
    }

    let mailboxNames = CkoStringTable()!
    mailboxNames.append(value: "INBOX")
    mailboxNames.append(value: allMail)
    let unique = CkoJsonObject()!
    let found = CkoMessageSet()!
    let uidStrings = CkoStringTable()!
    let raw = CkoStringBuilder()!
    let captures = CkoJsonObject()!
    var folderIndex: Int = 0
    while (folderIndex < mailboxNames.count.intValue) {
        var selected: String? = mailboxNames.string(at: folderIndex)
        success = imap.examineMailbox(mailbox: selected)
        if success != true {
            imap.logout()
            imap.disconnect()
            print("Could not open the mailbox read-only.")
            return
        }

        success = imap.queryMbx(criteria: "ALL", bUid: true, msgSet: found)
        if success != true {
            imap.logout()
            imap.disconnect()
            print("Could not obtain message UIDs.")
            return
        }

        uidStrings.clear()
        if found.count.intValue > 0 {
            uidStrings.splitAndAppend(inStr: found.toCommaSeparatedStr(), delimiterChar: ",", exceptDoubleQuoted: false, exceptEscaped: false)
        }

        //  Sample up to 10 messages from each mailbox; this is not a complete synchronization.
        var i: Int = 0
        while ((i < uidStrings.count.intValue) && (i < 10)) {
            var uid: String? = uidStrings.string(at: i)
            let joined1 = CkoStringBuilder()!
            joined1.append(value: "UID FETCH ")
            joined1.append(value: uid)
            joined1.append(value: " (UID X-GM-MSGID X-GM-THRID)")
            var response: String? = imap.sendRawCommand(rawCommand: joined1.getAsString())
            statusText.setString(value: response)
            //  A completed raw exchange can still return NO or BAD. Require tagged OK.
            completed = statusText.regexMatch(pattern: "(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z", json: statusMatch, timeoutMs: 1000).intValue

            if (imap.lastMethodSuccess != true) || (completed != 1) {
                imap.logout()
                imap.disconnect()
                print("Could not fetch Gmail IDs.")
                return
            }

            raw.setString(value: response)
            //  Match only this UID's metadata line. Attribute order need not be fixed.
            //  Unsolicited EXISTS/EXPUNGE/FLAGS lines do not match these three attributes.
            let joined2 = CkoStringBuilder()!
            joined2.append(value: "(?mi)^\\* [0-9]+ FETCH \\((?=[^\\r\\n]*\\bUID ")
            joined2.append(value: uid)
            joined2.append(value: "(?: |\\)))(?=[^\\r\\n]*\\bX-GM-MSGID ([0-9]+)(?: |\\)))(?=[^\\r\\n]*\\bX-GM-THRID ([0-9]+)(?: |\\)))[^\\r\\n]*\\)\\r?$")
            var pattern: String? = joined2.getAsString()
            var count: Int = raw.regexMatch(pattern: pattern, json: captures, timeoutMs: 1000).intValue
            if count < 0 {
                imap.logout()
                imap.disconnect()
                print("Could not parse the Gmail metadata response.")
                return
            }

            if count == 1 {
                var messageId: String? = captures.string(of: "match[0].group[1].cap")
                var threadId: String? = captures.string(of: "match[0].group[2].cap")
                if unique.index(of: messageId).intValue < 0 {
                    //  Direct JSON member names; both IDs remain strings without numeric conversion.
                    unique.appendString(name: messageId, value: threadId)
                    print("Message ID: \(messageId!)  Thread ID: \(threadId!)")
                }
                else {
                    print("Already encountered under another label: \(messageId!)")
                }

            }
            else {
                print("No single metadata row for UID \(uid!); it may have disappeared. Skipping.")
            }

            i = i + 1
        }

        folderIndex = folderIndex + 1
    }

    imap.logout()
    imap.disconnect()
    print("Unique sampled messages: \(unique.size.intValue)")

}