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

VB.NET
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

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

If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",True) = True)) Then
    Debug.WriteLine("Authorize or refresh the mailbox first.")
    Exit Sub
End If

Dim mailbox As String = "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
    Debug.WriteLine("Could not establish the Gmail IMAP TLS connection.")
    Exit Sub
End If

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

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

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

Dim allMail As String = ""
Dim folderMatches As Integer = 0
Dim f As Integer = 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
End While
If (folderMatches <> 1) Then
    imap.Logout()
    imap.Disconnect()
    Debug.WriteLine("Expected one selectable folder with the \All special-use attribute. Check label visibility.")
    Exit Sub
End If

Dim mailboxNames As New Chilkat.StringTable
mailboxNames.Append("INBOX")
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 Integer = 0
While (folderIndex < mailboxNames.Count)
    Dim selected As String = mailboxNames.StringAt(folderIndex)
    success = imap.ExamineMailbox(selected)
    If (success <> True) Then
        imap.Logout()
        imap.Disconnect()
        Debug.WriteLine("Could not open the mailbox read-only.")
        Exit Sub
    End If

    success = imap.QueryMbx("ALL",True,found)
    If (success <> True) Then
        imap.Logout()
        imap.Disconnect()
        Debug.WriteLine("Could not obtain message UIDs.")
        Exit Sub
    End If

    uidStrings.Clear()
    If (found.Count > 0) Then
        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 Integer = 0
    While ((i < uidStrings.Count) And (i < 10))
        Dim uid As String = uidStrings.StringAt(i)
        Dim joined1 As New Chilkat.StringBuilder
        joined1.Append("UID FETCH ")
        joined1.Append(uid)
        joined1.Append(" (UID X-GM-MSGID X-GM-THRID)")
        Dim response As String = imap.SendRawCommand(joined1.GetAsString())
        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
            imap.Logout()
            imap.Disconnect()
            Debug.WriteLine("Could not fetch Gmail IDs.")
            Exit Sub
        End If

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

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

        Else
            Debug.WriteLine("No single metadata row for UID " & uid & "; it may have disappeared. Skipping.")
        End If

        i = i + 1
    End While
    folderIndex = folderIndex + 1
End While
imap.Logout()
imap.Disconnect()
Debug.WriteLine("Unique sampled messages: " & unique.Size)