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.
Chilkat AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$oStatusText = ObjCreate("Chilkat.StringBuilder")
$oStatusMatch = ObjCreate("Chilkat.JsonObject")
Local $iCompleted
$oToken = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oToken.LoadFile("gmail-mail-token.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load the protocol token from the private working directory." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("Authorize or refresh the mailbox first." & @CRLF)
Exit
EndIf
Local $sMailbox = "user@example.com"
$oImap = ObjCreate("Chilkat.Imap")
$oImap.Ssl = True
$oImap.Port = 993
$oImap.RequireSslCertVerify = True
$oImap.AuthMethod = "XOAUTH2"
$bSuccess = $oImap.Connect("imap.gmail.com")
If ($bSuccess <> True) Then
ConsoleWrite("Could not establish the Gmail IMAP TLS connection." & @CRLF)
Exit
EndIf
$bSuccess = $oImap.Login($sMailbox,$oToken.StringOf("access_token"))
If ($bSuccess <> True) Then
$oImap.Disconnect()
ConsoleWrite("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy." & @CRLF)
Exit
EndIf
Local $sCapabilities = $oImap.Capability()
If (($oImap.LastMethodSuccess <> True) Or ($oImap.HasCapability("X-GM-EXT-1",$sCapabilities) <> True)) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Gmail IMAP extensions are unavailable." & @CRLF)
Exit
EndIf
$oFolders = ObjCreate("Chilkat.Mailboxes")
$bSuccess = $oImap.MbxList(False,"","*",$oFolders)
If ($bSuccess <> True) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not list Gmail folders." & @CRLF)
Exit
EndIf
Local $sAllMail = ""
Local $iFolderMatches = 0
Local $iF = 0
While ($iF < $oFolders.Count)
If (($oFolders.HasFlag($iF,"\All") = True) And ($oFolders.IsSelectable($iF) = True)) Then
$sAllMail = $oFolders.GetName($iF)
$iFolderMatches = $iFolderMatches + 1
EndIf
$iF = $iF + 1
Wend
If ($iFolderMatches <> 1) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Expected one selectable folder with the \All special-use attribute. Check label visibility." & @CRLF)
Exit
EndIf
$oMailboxNames = ObjCreate("Chilkat.StringTable")
$oMailboxNames.Append("INBOX")
$oMailboxNames.Append($sAllMail)
$oUnique = ObjCreate("Chilkat.JsonObject")
$oFound = ObjCreate("Chilkat.MessageSet")
$oUidStrings = ObjCreate("Chilkat.StringTable")
$oRaw = ObjCreate("Chilkat.StringBuilder")
$oCaptures = ObjCreate("Chilkat.JsonObject")
Local $iFolderIndex = 0
While ($iFolderIndex < $oMailboxNames.Count)
Local $selected = $oMailboxNames.StringAt($iFolderIndex)
$bSuccess = $oImap.ExamineMailbox($selected)
If ($bSuccess <> True) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not open the mailbox read-only." & @CRLF)
Exit
EndIf
$bSuccess = $oImap.QueryMbx("ALL",True,$oFound)
If ($bSuccess <> True) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not obtain message UIDs." & @CRLF)
Exit
EndIf
$oUidStrings.Clear
If ($oFound.Count > 0) Then
$oUidStrings.SplitAndAppend($oFound.ToCommaSeparatedStr(),",",False,False)
EndIf
; Sample up to 10 messages from each mailbox; this is not a complete synchronization.
Local $i = 0
While (($i < $oUidStrings.Count) And ($i < 10))
Local $sUid = $oUidStrings.StringAt($i)
$oJoined1 = ObjCreate("Chilkat.StringBuilder")
$oJoined1.Append("UID FETCH ")
$oJoined1.Append($sUid)
$oJoined1.Append(" (UID X-GM-MSGID X-GM-THRID)")
Local $sResponse = $oImap.SendRawCommand($oJoined1.GetAsString())
$oStatusText.SetString($sResponse)
; A completed raw exchange can still return NO or BAD. Require tagged OK.
$iCompleted = $oStatusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",$oStatusMatch,1000)
If (($oImap.LastMethodSuccess <> True) Or ($iCompleted <> 1)) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not fetch Gmail IDs." & @CRLF)
Exit
EndIf
$oRaw.SetString($sResponse)
; Match only this UID's metadata line. Attribute order need not be fixed.
; Unsolicited EXISTS/EXPUNGE/FLAGS lines do not match these three attributes.
$oJoined2 = ObjCreate("Chilkat.StringBuilder")
$oJoined2.Append("(?mi)^\* [0-9]+ FETCH \((?=[^\r\n]*\bUID ")
$oJoined2.Append($sUid)
$oJoined2.Append("(?: |\)))(?=[^\r\n]*\bX-GM-MSGID ([0-9]+)(?: |\)))(?=[^\r\n]*\bX-GM-THRID ([0-9]+)(?: |\)))[^\r\n]*\)\r?$")
Local $sPattern = $oJoined2.GetAsString()
Local $iCount = $oRaw.RegexMatch($sPattern,$oCaptures,1000)
If ($iCount < 0) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not parse the Gmail metadata response." & @CRLF)
Exit
EndIf
If ($iCount = 1) Then
Local $sMessageId = $oCaptures.StringOf("match[0].group[1].cap")
Local $sThreadId = $oCaptures.StringOf("match[0].group[2].cap")
If ($oUnique.IndexOf($sMessageId) < 0) Then
; Direct JSON member names; both IDs remain strings without numeric conversion.
$oUnique.AppendString($sMessageId,$sThreadId)
ConsoleWrite("Message ID: " & $sMessageId & " Thread ID: " & $sThreadId & @CRLF)
Else
ConsoleWrite("Already encountered under another label: " & $sMessageId & @CRLF)
EndIf
Else
ConsoleWrite("No single metadata row for UID " & $sUid & "; it may have disappeared. Skipping." & @CRLF)
EndIf
$i = $i + 1
Wend
$iFolderIndex = $iFolderIndex + 1
Wend
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Unique sampled messages: " & $oUnique.Size & @CRLF)