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

Xojo Plugin
Dim success As Boolean
success = False

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

Dim statusText As New Chilkat.StringBuilder
Dim statusMatch As New Chilkat.JsonObject
Dim completed As Int32
Dim token As New Chilkat.JsonObject
success = token.LoadFile("gmail-mail-token.json")
If (success <> True) Then
    System.DebugLog("Could not load the protocol token from the private working directory.")
    Return
End If

If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",True) = True)) Then
    System.DebugLog("Authorize or refresh the mailbox first.")
    Return
End If

Dim mailbox As String
mailbox = "user@example.com"
Dim imap As New Chilkat.Imap
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If (success <> True) Then
    System.DebugLog("Could not establish the Gmail IMAP TLS connection.")
    Return
End If

success = imap.Login(mailbox,token.StringOf("access_token"))
If (success <> True) Then
    success = imap.Disconnect()
    System.DebugLog("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
    Return
End If

Dim capabilities As String
capabilities = imap.Capability()
If ((imap.LastMethodSuccess <> True) Or (imap.HasCapability("X-GM-EXT-1",capabilities) <> True)) Then
    success = imap.Logout()
    success = imap.Disconnect()
    System.DebugLog("Gmail IMAP extensions are unavailable.")
    Return
End If

Dim folders As New Chilkat.Mailboxes
success = imap.MbxList(False,"","*",folders)
If (success <> True) Then
    success = imap.Logout()
    success = imap.Disconnect()
    System.DebugLog("Could not list Gmail folders.")
    Return
End If

Dim allMail As String
allMail = ""
Dim folderMatches As Int32
folderMatches = 0
Dim f As Int32
f = 0
While (f < folders.Count)
    If ((folders.HasFlag(f,"\All") = True) And (folders.IsSelectable(f) = True)) Then
        allMail = folders.GetName(f)
        folderMatches = folderMatches + 1
    End If

    f = f + 1
Wend
If (folderMatches <> 1) Then
    success = imap.Logout()
    success = imap.Disconnect()
    System.DebugLog("Expected one selectable folder with the \All special-use attribute. Check label visibility.")
    Return
End If

Dim mailboxNames As New Chilkat.StringTable
success = mailboxNames.Append("INBOX")
success = mailboxNames.Append(allMail)
Dim unique As New Chilkat.JsonObject
Dim found As New Chilkat.MessageSet
Dim uidStrings As New Chilkat.StringTable
Dim raw As New Chilkat.StringBuilder
Dim captures As New Chilkat.JsonObject
Dim folderIndex As Int32
folderIndex = 0
While (folderIndex < mailboxNames.Count)
    Dim selected As String
    selected = mailboxNames.StringAt(folderIndex)
    success = imap.ExamineMailbox(selected)
    If (success <> True) Then
        success = imap.Logout()
        success = imap.Disconnect()
        System.DebugLog("Could not open the mailbox read-only.")
        Return
    End If

    success = imap.QueryMbx("ALL",True,found)
    If (success <> True) Then
        success = imap.Logout()
        success = imap.Disconnect()
        System.DebugLog("Could not obtain message UIDs.")
        Return
    End If

    uidStrings.Clear 
    If (found.Count > 0) Then
        success = uidStrings.SplitAndAppend(found.ToCommaSeparatedStr(),",",False,False)
    End If

    //  Sample up to 10 messages from each mailbox; this is not a complete synchronization.
    Dim i As Int32
    i = 0
    While ((i < uidStrings.Count) And (i < 10))
        Dim uid As String
        uid = uidStrings.StringAt(i)
        Dim joined1 As New Chilkat.StringBuilder
        success = joined1.Append("UID FETCH ")
        success = joined1.Append(uid)
        success = joined1.Append(" (UID X-GM-MSGID X-GM-THRID)")
        Dim response As String
        response = imap.SendRawCommand(joined1.GetAsString())
        success = statusText.SetString(response)
        //  A completed raw exchange can still return NO or BAD. Require tagged OK.
        completed = statusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",statusMatch,1000)

        If ((imap.LastMethodSuccess <> True) Or (completed <> 1)) Then
            success = imap.Logout()
            success = imap.Disconnect()
            System.DebugLog("Could not fetch Gmail IDs.")
            Return
        End If

        success = raw.SetString(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.
        Dim joined2 As New Chilkat.StringBuilder
        success = joined2.Append("(?mi)^\* [0-9]+ FETCH \((?=[^\r\n]*\bUID ")
        success = joined2.Append(uid)
        success = joined2.Append("(?: |\)))(?=[^\r\n]*\bX-GM-MSGID ([0-9]+)(?: |\)))(?=[^\r\n]*\bX-GM-THRID ([0-9]+)(?: |\)))[^\r\n]*\)\r?$")
        Dim pattern As String
        pattern = joined2.GetAsString()
        Dim count As Int32
        count = raw.RegexMatch(pattern,captures,1000)
        If (count < 0) Then
            success = imap.Logout()
            success = imap.Disconnect()
            System.DebugLog("Could not parse the Gmail metadata response.")
            Return
        End If

        If (count = 1) Then
            Dim messageId As String
            messageId = captures.StringOf("match[0].group[1].cap")
            Dim threadId As String
            threadId = captures.StringOf("match[0].group[2].cap")
            If (unique.IndexOf(messageId) < 0) Then
                //  Direct JSON member names; both IDs remain strings without numeric conversion.
                success = unique.AppendString(messageId,threadId)
                System.DebugLog("Message ID: " + messageId + "  Thread ID: " + threadId)
            Else
                System.DebugLog("Already encountered under another label: " + messageId)
            End If

        Else
            System.DebugLog("No single metadata row for UID " + uid + "; it may have disappeared. Skipping.")
        End If

        i = i + 1
    Wend
    folderIndex = folderIndex + 1
Wend
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Unique sampled messages: " + Str(unique.Size))