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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoStatusText
    Variant vStatusMatch
    Handle hoStatusMatch
    Integer iCompleted
    Handle hoToken
    String sMailbox
    Handle hoImap
    String sCapabilities
    Variant vFolders
    Handle hoFolders
    String sAllMail
    Integer iFolderMatches
    Integer f
    Handle hoMailboxNames
    Handle hoUnique
    Variant vFound
    Handle hoFound
    Handle hoUidStrings
    Handle hoRaw
    Variant vCaptures
    Handle hoCaptures
    Integer iFolderIndex
    String sSelected
    Integer i
    String sUid
    Handle hoJoined1
    String sResponse
    Handle hoJoined2
    String sPattern
    Integer iCount
    String sMessageId
    String sThreadId
    String sTemp1
    Integer iTemp1
    Boolean bTemp1
    Boolean bTemp2

    Move False To iSuccess

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

    Get Create (RefClass(cComChilkatStringBuilder)) To hoStatusText
    If (Not(IsComObjectCreated(hoStatusText))) Begin
        Send CreateComObject of hoStatusText
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoStatusMatch
    If (Not(IsComObjectCreated(hoStatusMatch))) Begin
        Send CreateComObject of hoStatusMatch
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Get ComLoadFile Of hoToken "gmail-mail-token.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load the protocol token from the private working directory."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
    Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "Authorize or refresh the mailbox first."
        Procedure_Return
    End

    Move "user@example.com" To sMailbox
    Get Create (RefClass(cComChilkatImap)) To hoImap
    If (Not(IsComObjectCreated(hoImap))) Begin
        Send CreateComObject of hoImap
    End
    Set ComSsl Of hoImap To True
    Set ComPort Of hoImap To 993
    Set ComRequireSslCertVerify Of hoImap To True
    Set ComAuthMethod Of hoImap To "XOAUTH2"
    Get ComConnect Of hoImap "imap.gmail.com" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not establish the Gmail IMAP TLS connection."
        Procedure_Return
    End

    Get ComStringOf Of hoToken "access_token" To sTemp1
    Get ComLogin Of hoImap sMailbox sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Get ComDisconnect Of hoImap To iSuccess
        Showln "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
        Procedure_Return
    End

    Get ComCapability Of hoImap To sCapabilities
    Get ComLastMethodSuccess Of hoImap To bTemp1
    Get ComHasCapability Of hoImap "X-GM-EXT-1" sCapabilities To bTemp2
    If ((bTemp1 <> True) Or (bTemp2 <> True)) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Gmail IMAP extensions are unavailable."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatMailboxes)) To hoFolders
    If (Not(IsComObjectCreated(hoFolders))) Begin
        Send CreateComObject of hoFolders
    End
    Get pvComObject of hoFolders to vFolders
    Get ComMbxList Of hoImap False "" "*" vFolders To iSuccess
    If (iSuccess <> True) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Could not list Gmail folders."
        Procedure_Return
    End

    Move "" To sAllMail
    Move 0 To iFolderMatches
    Move 0 To f
    While (f < (ComCount(hoFolders)))
        Get ComHasFlag Of hoFolders f "\All" To bTemp1
        Get ComIsSelectable Of hoFolders f To bTemp2
        If ((bTemp1 = True) And (bTemp2 = True)) Begin
            Get ComGetName Of hoFolders f To sAllMail
            Move (iFolderMatches + 1) To iFolderMatches
        End

        Move (f + 1) To f
    Loop

    If (iFolderMatches <> 1) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Expected one selectable folder with the \All special-use attribute. Check label visibility."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringTable)) To hoMailboxNames
    If (Not(IsComObjectCreated(hoMailboxNames))) Begin
        Send CreateComObject of hoMailboxNames
    End
    Get ComAppend Of hoMailboxNames "INBOX" To iSuccess
    Get ComAppend Of hoMailboxNames sAllMail To iSuccess
    Get Create (RefClass(cComChilkatJsonObject)) To hoUnique
    If (Not(IsComObjectCreated(hoUnique))) Begin
        Send CreateComObject of hoUnique
    End
    Get Create (RefClass(cComChilkatMessageSet)) To hoFound
    If (Not(IsComObjectCreated(hoFound))) Begin
        Send CreateComObject of hoFound
    End
    Get Create (RefClass(cComChilkatStringTable)) To hoUidStrings
    If (Not(IsComObjectCreated(hoUidStrings))) Begin
        Send CreateComObject of hoUidStrings
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoRaw
    If (Not(IsComObjectCreated(hoRaw))) Begin
        Send CreateComObject of hoRaw
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoCaptures
    If (Not(IsComObjectCreated(hoCaptures))) Begin
        Send CreateComObject of hoCaptures
    End
    Move 0 To iFolderIndex
    While (iFolderIndex < (ComCount(hoMailboxNames)))
        Get ComStringAt Of hoMailboxNames iFolderIndex To sSelected
        Get ComExamineMailbox Of hoImap sSelected To iSuccess
        If (iSuccess <> True) Begin
            Get ComLogout Of hoImap To iSuccess
            Get ComDisconnect Of hoImap To iSuccess
            Showln "Could not open the mailbox read-only."
            Procedure_Return
        End

        Get pvComObject of hoFound to vFound
        Get ComQueryMbx Of hoImap "ALL" True vFound To iSuccess
        If (iSuccess <> True) Begin
            Get ComLogout Of hoImap To iSuccess
            Get ComDisconnect Of hoImap To iSuccess
            Showln "Could not obtain message UIDs."
            Procedure_Return
        End

        Send ComClear To hoUidStrings
        Get ComCount Of hoFound To iTemp1
        If (iTemp1 > 0) Begin
            Get ComToCommaSeparatedStr Of hoFound To sTemp1
            Get ComSplitAndAppend Of hoUidStrings sTemp1 "," False False To iSuccess
        End

        //  Sample up to 10 messages from each mailbox; this is not a complete synchronization.
        Move 0 To i
        While ((i < (ComCount(hoUidStrings))) And (i < 10))
            Get ComStringAt Of hoUidStrings i To sUid
            Get Create (RefClass(cComChilkatStringBuilder)) To hoJoined1
            If (Not(IsComObjectCreated(hoJoined1))) Begin
                Send CreateComObject of hoJoined1
            End
            Get ComAppend Of hoJoined1 "UID FETCH " To iSuccess
            Get ComAppend Of hoJoined1 sUid To iSuccess
            Get ComAppend Of hoJoined1 " (UID X-GM-MSGID X-GM-THRID)" To iSuccess
            Get ComGetAsString Of hoJoined1 To sTemp1
            Get ComSendRawCommand Of hoImap sTemp1 To sResponse
            Get ComSetString Of hoStatusText sResponse To iSuccess
            //  A completed raw exchange can still return NO or BAD. Require tagged OK.
            Get pvComObject of hoStatusMatch to vStatusMatch
            Get ComRegexMatch Of hoStatusText "(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z" vStatusMatch 1000 To iCompleted

            Get ComLastMethodSuccess Of hoImap To bTemp1
            If ((bTemp1 <> True) Or (iCompleted <> 1)) Begin
                Get ComLogout Of hoImap To iSuccess
                Get ComDisconnect Of hoImap To iSuccess
                Showln "Could not fetch Gmail IDs."
                Procedure_Return
            End

            Get ComSetString Of hoRaw sResponse To iSuccess
            //  Match only this UID's metadata line. Attribute order need not be fixed.
            //  Unsolicited EXISTS/EXPUNGE/FLAGS lines do not match these three attributes.
            Get Create (RefClass(cComChilkatStringBuilder)) To hoJoined2
            If (Not(IsComObjectCreated(hoJoined2))) Begin
                Send CreateComObject of hoJoined2
            End
            Get ComAppend Of hoJoined2 "(?mi)^\* [0-9]+ FETCH \((?=[^\r\n]*\bUID " To iSuccess
            Get ComAppend Of hoJoined2 sUid To iSuccess
            Get ComAppend Of hoJoined2 "(?: |\)))(?=[^\r\n]*\bX-GM-MSGID ([0-9]+)(?: |\)))(?=[^\r\n]*\bX-GM-THRID ([0-9]+)(?: |\)))[^\r\n]*\)\r?$" To iSuccess
            Get ComGetAsString Of hoJoined2 To sPattern
            Get pvComObject of hoCaptures to vCaptures
            Get ComRegexMatch Of hoRaw sPattern vCaptures 1000 To iCount
            If (iCount < 0) Begin
                Get ComLogout Of hoImap To iSuccess
                Get ComDisconnect Of hoImap To iSuccess
                Showln "Could not parse the Gmail metadata response."
                Procedure_Return
            End

            If (iCount = 1) Begin
                Get ComStringOf Of hoCaptures "match[0].group[1].cap" To sMessageId
                Get ComStringOf Of hoCaptures "match[0].group[2].cap" To sThreadId
                Get ComIndexOf Of hoUnique sMessageId To iTemp1
                If (iTemp1 < 0) Begin
                    //  Direct JSON member names; both IDs remain strings without numeric conversion.
                    Get ComAppendString Of hoUnique sMessageId sThreadId To iSuccess
                    Showln "Message ID: " sMessageId "  Thread ID: " sThreadId
                End
                Else Begin
                    Showln "Already encountered under another label: " sMessageId
                End

            End
            Else Begin
                Showln "No single metadata row for UID " sUid "; it may have disappeared. Skipping."
            End

            Move (i + 1) To i
        Loop

        Move (iFolderIndex + 1) To iFolderIndex
    Loop

    Get ComLogout Of hoImap To iSuccess
    Get ComDisconnect Of hoImap To iSuccess
    Get ComSize Of hoUnique To iTemp1
    Showln "Unique sampled messages: " iTemp1


End_Procedure