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 B4X Downloads
Dim success As Boolean = False
' Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim statusText As ChilkatStringBuilder
statusText.Initialize
Dim statusMatch As ChilkatJsonObject
statusMatch.Initialize
Dim completed As Int
Dim token As ChilkatJsonObject
token.Initialize
success = token.LoadFile("gmail-mail-token.json")
If success <> True Then
Log("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
Log("Authorize or refresh the mailbox first.")
Return
End If
Dim mailbox As String = "user@example.com"
Dim imap As ChilkatImap
imap.Initialize("imap")
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If success <> True Then
Log("Could not establish the Gmail IMAP TLS connection.")
Return
End If
success = imap.Login(mailbox, token.StringOf("access_token"))
If success <> True Then
imap.Disconnect
Log("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
Return
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
Log("Gmail IMAP extensions are unavailable.")
Return
End If
Dim folders As ChilkatMailboxes
folders.Initialize
success = imap.MbxList(False, "", "*", folders)
If success <> True Then
imap.Logout
imap.Disconnect
Log("Could not list Gmail folders.")
Return
End If
Dim allMail As String = ""
Dim folderMatches As Int = 0
Dim f As Int = 0
Do 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
Loop
If folderMatches <> 1 Then
imap.Logout
imap.Disconnect
Log("Expected one selectable folder with the \All special-use attribute. Check label visibility.")
Return
End If
Dim mailboxNames As ChilkatStringTable
mailboxNames.Initialize
mailboxNames.Append("INBOX")
mailboxNames.Append(allMail)
Dim unique As ChilkatJsonObject
unique.Initialize
Dim found As ChilkatMessageSet
found.Initialize
Dim uidStrings As ChilkatStringTable
uidStrings.Initialize
Dim raw As ChilkatStringBuilder
raw.Initialize
Dim captures As ChilkatJsonObject
captures.Initialize
Dim folderIndex As Int = 0
Do While (folderIndex < mailboxNames.Count)
Dim selected As String = mailboxNames.StringAt(folderIndex)
success = imap.ExamineMailbox(selected)
If success <> True Then
imap.Logout
imap.Disconnect
Log("Could not open the mailbox read-only.")
Return
End If
success = imap.QueryMbx("ALL", True, found)
If success <> True Then
imap.Logout
imap.Disconnect
Log("Could not obtain message UIDs.")
Return
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 Int = 0
Do While ((i < uidStrings.Count) And (i < 10))
Dim uid As String = uidStrings.StringAt(i)
Dim joined1 As ChilkatStringBuilder
joined1.Initialize
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
Log("Could not fetch Gmail IDs.")
Return
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 ChilkatStringBuilder
joined2.Initialize
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 Int = raw.RegexMatch(pattern, captures, 1000)
If count < 0 Then
imap.Logout
imap.Disconnect
Log("Could not parse the Gmail metadata response.")
Return
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)
Log("Message ID: " & messageId & " Thread ID: " & threadId)
Else
Log("Already encountered under another label: " & messageId)
End If
Else
Log("No single metadata row for UID " & uid & "; it may have disappeared. Skipping.")
End If
i = i + 1
Loop
folderIndex = folderIndex + 1
Loop
imap.Logout
imap.Disconnect
Log("Unique sampled messages: " & unique.Size)