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 Classic ASP Downloads
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
success = 0
' Assumes Chilkat is unlocked. See Global Unlock Sample.
set statusText = Server.CreateObject("Chilkat.StringBuilder")
set statusMatch = Server.CreateObject("Chilkat.JsonObject")
set token = Server.CreateObject("Chilkat.JsonObject")
success = token.LoadFile("gmail-mail-token.json")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not load the protocol token from the private working directory.") & "</pre>"
Response.End
End If
If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",1) = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Authorize or refresh the mailbox first.") & "</pre>"
Response.End
End If
mailbox = "user@example.com"
set imap = Server.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
Response.Write "<pre>" & Server.HTMLEncode( "Could not establish the Gmail IMAP TLS connection.") & "</pre>"
Response.End
End If
success = imap.Login(mailbox,token.StringOf("access_token"))
If (success <> 1) Then
success = imap.Disconnect()
Response.Write "<pre>" & Server.HTMLEncode( "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.") & "</pre>"
Response.End
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()
Response.Write "<pre>" & Server.HTMLEncode( "Gmail IMAP extensions are unavailable.") & "</pre>"
Response.End
End If
set folders = Server.CreateObject("Chilkat.Mailboxes")
success = imap.MbxList(0,"","*",folders)
If (success <> 1) Then
success = imap.Logout()
success = imap.Disconnect()
Response.Write "<pre>" & Server.HTMLEncode( "Could not list Gmail folders.") & "</pre>"
Response.End
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()
Response.Write "<pre>" & Server.HTMLEncode( "Expected one selectable folder with the \All special-use attribute. Check label visibility.") & "</pre>"
Response.End
End If
set mailboxNames = Server.CreateObject("Chilkat.StringTable")
success = mailboxNames.Append("INBOX")
success = mailboxNames.Append(allMail)
set unique = Server.CreateObject("Chilkat.JsonObject")
set found = Server.CreateObject("Chilkat.MessageSet")
set uidStrings = Server.CreateObject("Chilkat.StringTable")
set raw = Server.CreateObject("Chilkat.StringBuilder")
set captures = Server.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()
Response.Write "<pre>" & Server.HTMLEncode( "Could not open the mailbox read-only.") & "</pre>"
Response.End
End If
success = imap.QueryMbx("ALL",1,found)
If (success <> 1) Then
success = imap.Logout()
success = imap.Disconnect()
Response.Write "<pre>" & Server.HTMLEncode( "Could not obtain message UIDs.") & "</pre>"
Response.End
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 = Server.CreateObject("Chilkat.StringBuilder")
success = joined1.Append("UID FETCH ")
success = joined1.Append(uid)
success = joined1.Append(" (UID X-GM-MSGID X-GM-THRID)")
ERROR: ASP example cannot use request or response as a variable name.
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()
Response.Write "<pre>" & Server.HTMLEncode( "Could not fetch Gmail IDs.") & "</pre>"
Response.End
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 = Server.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()
Response.Write "<pre>" & Server.HTMLEncode( "Could not parse the Gmail metadata response.") & "</pre>"
Response.End
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)
Response.Write "<pre>" & Server.HTMLEncode( "Message ID: " & messageId & " Thread ID: " & threadId) & "</pre>"
Else
Response.Write "<pre>" & Server.HTMLEncode( "Already encountered under another label: " & messageId) & "</pre>"
End If
Else
Response.Write "<pre>" & Server.HTMLEncode( "No single metadata row for UID " & uid & "; it may have disappeared. Skipping.") & "</pre>"
End If
i = i + 1
Loop
folderIndex = folderIndex + 1
Loop
success = imap.Logout()
success = imap.Disconnect()
Response.Write "<pre>" & Server.HTMLEncode( "Unique sampled messages: " & unique.Size) & "</pre>"
%>
</body>
</html>