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

VBScript
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)

success = 0

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

set statusText = CreateObject("Chilkat.StringBuilder")
set statusMatch = CreateObject("Chilkat.JsonObject")

set token = CreateObject("Chilkat.JsonObject")
success = token.LoadFile("gmail-mail-token.json")
If (success <> 1) Then
    outFile.WriteLine("Could not load the protocol token from the private working directory.")
    WScript.Quit
End If

If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",1) = 1)) Then
    outFile.WriteLine("Authorize or refresh the mailbox first.")
    WScript.Quit
End If

mailbox = "user@example.com"
set imap = CreateObject("Chilkat.Imap")
imap.Ssl = 1
imap.Port = 993
imap.RequireSslCertVerify = 1
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If (success <> 1) Then
    outFile.WriteLine("Could not establish the Gmail IMAP TLS connection.")
    WScript.Quit
End If

success = imap.Login(mailbox,token.StringOf("access_token"))
If (success <> 1) Then
    success = imap.Disconnect()
    outFile.WriteLine("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
    WScript.Quit
End If

capabilities = imap.Capability()
If ((imap.LastMethodSuccess <> 1) Or (imap.HasCapability("X-GM-EXT-1",capabilities) <> 1)) Then
    success = imap.Logout()
    success = imap.Disconnect()
    outFile.WriteLine("Gmail IMAP extensions are unavailable.")
    WScript.Quit
End If

set folders = CreateObject("Chilkat.Mailboxes")
success = imap.MbxList(0,"","*",folders)
If (success <> 1) Then
    success = imap.Logout()
    success = imap.Disconnect()
    outFile.WriteLine("Could not list Gmail folders.")
    WScript.Quit
End If

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

    f = f + 1
Loop
If (folderMatches <> 1) Then
    success = imap.Logout()
    success = imap.Disconnect()
    outFile.WriteLine("Expected one selectable folder with the \All special-use attribute. Check label visibility.")
    WScript.Quit
End If

set mailboxNames = CreateObject("Chilkat.StringTable")
success = mailboxNames.Append("INBOX")
success = mailboxNames.Append(allMail)
set unique = CreateObject("Chilkat.JsonObject")
set found = CreateObject("Chilkat.MessageSet")
set uidStrings = CreateObject("Chilkat.StringTable")
set raw = CreateObject("Chilkat.StringBuilder")
set captures = CreateObject("Chilkat.JsonObject")
folderIndex = 0
Do While (folderIndex < mailboxNames.Count)
    selected = mailboxNames.StringAt(folderIndex)
    success = imap.ExamineMailbox(selected)
    If (success <> 1) Then
        success = imap.Logout()
        success = imap.Disconnect()
        outFile.WriteLine("Could not open the mailbox read-only.")
        WScript.Quit
    End If

    success = imap.QueryMbx("ALL",1,found)
    If (success <> 1) Then
        success = imap.Logout()
        success = imap.Disconnect()
        outFile.WriteLine("Could not obtain message UIDs.")
        WScript.Quit
    End If

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

    '  Sample up to 10 messages from each mailbox; this is not a complete synchronization.
    i = 0
    Do While ((i < uidStrings.Count) And (i < 10))
        uid = uidStrings.StringAt(i)
        set joined1 = CreateObject("Chilkat.StringBuilder")
        success = joined1.Append("UID FETCH ")
        success = joined1.Append(uid)
        success = joined1.Append(" (UID X-GM-MSGID X-GM-THRID)")
        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 <> 1) Or (completed <> 1)) Then
            success = imap.Logout()
            success = imap.Disconnect()
            outFile.WriteLine("Could not fetch Gmail IDs.")
            WScript.Quit
        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.
        set joined2 = CreateObject("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?$")
        pattern = joined2.GetAsString()
        count = raw.RegexMatch(pattern,captures,1000)
        If (count < 0) Then
            success = imap.Logout()
            success = imap.Disconnect()
            outFile.WriteLine("Could not parse the Gmail metadata response.")
            WScript.Quit
        End If

        If (count = 1) Then
            messageId = captures.StringOf("match[0].group[1].cap")
            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)
                outFile.WriteLine("Message ID: " & messageId & "  Thread ID: " & threadId)
            Else
                outFile.WriteLine("Already encountered under another label: " & messageId)
            End If

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

        i = i + 1
    Loop
    folderIndex = folderIndex + 1
Loop
success = imap.Logout()
success = imap.Disconnect()
outFile.WriteLine("Unique sampled messages: " & unique.Size)

outFile.Close