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

PureBasic
IncludeFile "CkJsonObject.pb"
IncludeFile "CkMessageSet.pb"
IncludeFile "CkMailboxes.pb"
IncludeFile "CkImap.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkStringTable.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.

    statusText.i = CkStringBuilder::ckCreate()
    If statusText.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    statusMatch.i = CkJsonObject::ckCreate()
    If statusMatch.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    completed.i
    token.i = CkJsonObject::ckCreate()
    If token.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoadFile(token,"gmail-mail-token.json")
    If success <> 1
        Debug "Could not load the protocol token from the private working directory."
        CkStringBuilder::ckDispose(statusText)
        CkJsonObject::ckDispose(statusMatch)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(token,"access_token") <> 1) OR (CkJsonObject::ckStringOfEquals(token,"access_token","",1) = 1)
        Debug "Authorize or refresh the mailbox first."
        CkStringBuilder::ckDispose(statusText)
        CkJsonObject::ckDispose(statusMatch)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    mailbox.s = "user@example.com"
    imap.i = CkImap::ckCreate()
    If imap.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkImap::setCkSsl(imap, 1)
    CkImap::setCkPort(imap, 993)
    CkImap::setCkRequireSslCertVerify(imap, 1)
    CkImap::setCkAuthMethod(imap, "XOAUTH2")
    success = CkImap::ckConnect(imap,"imap.gmail.com")
    If success <> 1
        Debug "Could not establish the Gmail IMAP TLS connection."
        CkStringBuilder::ckDispose(statusText)
        CkJsonObject::ckDispose(statusMatch)
        CkJsonObject::ckDispose(token)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    success = CkImap::ckLogin(imap,mailbox,CkJsonObject::ckStringOf(token,"access_token"))
    If success <> 1
        CkImap::ckDisconnect(imap)
        Debug "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
        CkStringBuilder::ckDispose(statusText)
        CkJsonObject::ckDispose(statusMatch)
        CkJsonObject::ckDispose(token)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    capabilities.s = CkImap::ckCapability(imap)
    If (CkImap::ckLastMethodSuccess(imap) <> 1) OR (CkImap::ckHasCapability(imap,"X-GM-EXT-1",capabilities) <> 1)
        CkImap::ckLogout(imap)
        CkImap::ckDisconnect(imap)
        Debug "Gmail IMAP extensions are unavailable."
        CkStringBuilder::ckDispose(statusText)
        CkJsonObject::ckDispose(statusMatch)
        CkJsonObject::ckDispose(token)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    folders.i = CkMailboxes::ckCreate()
    If folders.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkImap::ckMbxList(imap,0,"","*",folders)
    If success <> 1
        CkImap::ckLogout(imap)
        CkImap::ckDisconnect(imap)
        Debug "Could not list Gmail folders."
        CkStringBuilder::ckDispose(statusText)
        CkJsonObject::ckDispose(statusMatch)
        CkJsonObject::ckDispose(token)
        CkImap::ckDispose(imap)
        CkMailboxes::ckDispose(folders)
        ProcedureReturn
    EndIf

    allMail.s = ""
    folderMatches.i = 0
    f.i = 0
    While (f < CkMailboxes::ckCount(folders))
        If (CkMailboxes::ckHasFlag(folders,f,"\All") = 1) AND (CkMailboxes::ckIsSelectable(folders,f) = 1)
            allMail = CkMailboxes::ckGetName(folders,f)
            folderMatches = folderMatches + 1
        EndIf

        f = f + 1
    Wend
    If folderMatches <> 1
        CkImap::ckLogout(imap)
        CkImap::ckDisconnect(imap)
        Debug "Expected one selectable folder with the \All special-use attribute. Check label visibility."
        CkStringBuilder::ckDispose(statusText)
        CkJsonObject::ckDispose(statusMatch)
        CkJsonObject::ckDispose(token)
        CkImap::ckDispose(imap)
        CkMailboxes::ckDispose(folders)
        ProcedureReturn
    EndIf

    mailboxNames.i = CkStringTable::ckCreate()
    If mailboxNames.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringTable::ckAppend(mailboxNames,"INBOX")
    CkStringTable::ckAppend(mailboxNames,allMail)
    unique.i = CkJsonObject::ckCreate()
    If unique.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    found.i = CkMessageSet::ckCreate()
    If found.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    uidStrings.i = CkStringTable::ckCreate()
    If uidStrings.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    raw.i = CkStringBuilder::ckCreate()
    If raw.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    captures.i = CkJsonObject::ckCreate()
    If captures.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    folderIndex.i = 0
    While (folderIndex < CkStringTable::ckCount(mailboxNames))
        selected.s = CkStringTable::ckStringAt(mailboxNames,folderIndex)
        success = CkImap::ckExamineMailbox(imap,selected)
        If success <> 1
            CkImap::ckLogout(imap)
            CkImap::ckDisconnect(imap)
            Debug "Could not open the mailbox read-only."
            CkStringBuilder::ckDispose(statusText)
            CkJsonObject::ckDispose(statusMatch)
            CkJsonObject::ckDispose(token)
            CkImap::ckDispose(imap)
            CkMailboxes::ckDispose(folders)
            CkStringTable::ckDispose(mailboxNames)
            CkJsonObject::ckDispose(unique)
            CkMessageSet::ckDispose(found)
            CkStringTable::ckDispose(uidStrings)
            CkStringBuilder::ckDispose(raw)
            CkJsonObject::ckDispose(captures)
            ProcedureReturn
        EndIf

        success = CkImap::ckQueryMbx(imap,"ALL",1,found)
        If success <> 1
            CkImap::ckLogout(imap)
            CkImap::ckDisconnect(imap)
            Debug "Could not obtain message UIDs."
            CkStringBuilder::ckDispose(statusText)
            CkJsonObject::ckDispose(statusMatch)
            CkJsonObject::ckDispose(token)
            CkImap::ckDispose(imap)
            CkMailboxes::ckDispose(folders)
            CkStringTable::ckDispose(mailboxNames)
            CkJsonObject::ckDispose(unique)
            CkMessageSet::ckDispose(found)
            CkStringTable::ckDispose(uidStrings)
            CkStringBuilder::ckDispose(raw)
            CkJsonObject::ckDispose(captures)
            ProcedureReturn
        EndIf

        CkStringTable::ckClear(uidStrings)
        If CkMessageSet::ckCount(found) > 0
            CkStringTable::ckSplitAndAppend(uidStrings,CkMessageSet::ckToCommaSeparatedStr(found),",",0,0)
        EndIf

        ;  Sample up to 10 messages from each mailbox; this is not a complete synchronization.
        i.i = 0
        While ((i < CkStringTable::ckCount(uidStrings)) AND (i < 10))
            uid.s = CkStringTable::ckStringAt(uidStrings,i)
            joined1.i = CkStringBuilder::ckCreate()
            If joined1.i = 0
                Debug "Failed to create object."
                ProcedureReturn
            EndIf

            CkStringBuilder::ckAppend(joined1,"UID FETCH ")
            CkStringBuilder::ckAppend(joined1,uid)
            CkStringBuilder::ckAppend(joined1," (UID X-GM-MSGID X-GM-THRID)")
            response.s = CkImap::ckSendRawCommand(imap,CkStringBuilder::ckGetAsString(joined1))
            CkStringBuilder::ckSetString(statusText,response)
            ;  A completed raw exchange can still return NO or BAD. Require tagged OK.
            completed = CkStringBuilder::ckRegexMatch(statusText,"(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",statusMatch,1000)

            If (CkImap::ckLastMethodSuccess(imap) <> 1) OR (completed <> 1)
                CkImap::ckLogout(imap)
                CkImap::ckDisconnect(imap)
                Debug "Could not fetch Gmail IDs."
                CkStringBuilder::ckDispose(statusText)
                CkJsonObject::ckDispose(statusMatch)
                CkJsonObject::ckDispose(token)
                CkImap::ckDispose(imap)
                CkMailboxes::ckDispose(folders)
                CkStringTable::ckDispose(mailboxNames)
                CkJsonObject::ckDispose(unique)
                CkMessageSet::ckDispose(found)
                CkStringTable::ckDispose(uidStrings)
                CkStringBuilder::ckDispose(raw)
                CkJsonObject::ckDispose(captures)
                CkStringBuilder::ckDispose(joined1)
                ProcedureReturn
            EndIf

            CkStringBuilder::ckSetString(raw,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.
            joined2.i = CkStringBuilder::ckCreate()
            If joined2.i = 0
                Debug "Failed to create object."
                ProcedureReturn
            EndIf

            CkStringBuilder::ckAppend(joined2,"(?mi)^\* [0-9]+ FETCH \((?=[^\r\n]*\bUID ")
            CkStringBuilder::ckAppend(joined2,uid)
            CkStringBuilder::ckAppend(joined2,"(?: |\)))(?=[^\r\n]*\bX-GM-MSGID ([0-9]+)(?: |\)))(?=[^\r\n]*\bX-GM-THRID ([0-9]+)(?: |\)))[^\r\n]*\)\r?$")
            pattern.s = CkStringBuilder::ckGetAsString(joined2)
            count.i = CkStringBuilder::ckRegexMatch(raw,pattern,captures,1000)
            If count < 0
                CkImap::ckLogout(imap)
                CkImap::ckDisconnect(imap)
                Debug "Could not parse the Gmail metadata response."
                CkStringBuilder::ckDispose(statusText)
                CkJsonObject::ckDispose(statusMatch)
                CkJsonObject::ckDispose(token)
                CkImap::ckDispose(imap)
                CkMailboxes::ckDispose(folders)
                CkStringTable::ckDispose(mailboxNames)
                CkJsonObject::ckDispose(unique)
                CkMessageSet::ckDispose(found)
                CkStringTable::ckDispose(uidStrings)
                CkStringBuilder::ckDispose(raw)
                CkJsonObject::ckDispose(captures)
                CkStringBuilder::ckDispose(joined1)
                CkStringBuilder::ckDispose(joined2)
                ProcedureReturn
            EndIf

            If count = 1
                messageId.s = CkJsonObject::ckStringOf(captures,"match[0].group[1].cap")
                threadId.s = CkJsonObject::ckStringOf(captures,"match[0].group[2].cap")
                If CkJsonObject::ckIndexOf(unique,messageId) < 0
                    ;  Direct JSON member names; both IDs remain strings without numeric conversion.
                    CkJsonObject::ckAppendString(unique,messageId,threadId)
                    Debug "Message ID: " + messageId + "  Thread ID: " + threadId
                Else
                    Debug "Already encountered under another label: " + messageId
                EndIf

            Else
                Debug "No single metadata row for UID " + uid + "; it may have disappeared. Skipping."
            EndIf

            i = i + 1
        Wend
        folderIndex = folderIndex + 1
    Wend
    CkImap::ckLogout(imap)
    CkImap::ckDisconnect(imap)
    Debug "Unique sampled messages: " + Str(CkJsonObject::ckSize(unique))


    CkStringBuilder::ckDispose(statusText)
    CkJsonObject::ckDispose(statusMatch)
    CkJsonObject::ckDispose(token)
    CkImap::ckDispose(imap)
    CkMailboxes::ckDispose(folders)
    CkStringTable::ckDispose(mailboxNames)
    CkJsonObject::ckDispose(unique)
    CkMessageSet::ckDispose(found)
    CkStringTable::ckDispose(uidStrings)
    CkStringBuilder::ckDispose(raw)
    CkJsonObject::ckDispose(captures)
    CkStringBuilder::ckDispose(joined1)
    CkStringBuilder::ckDispose(joined2)


    ProcedureReturn
EndProcedure