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 PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_StatusText
oleobject loo_StatusMatch
long li_Completed
oleobject loo_Token
string ls_Mailbox
oleobject loo_Imap
string ls_Capabilities
oleobject loo_Folders
string ls_AllMail
long li_FolderMatches
long f
oleobject loo_MailboxNames
oleobject loo_Unique
oleobject loo_Found
oleobject loo_UidStrings
oleobject loo_Raw
oleobject loo_Captures
long li_FolderIndex
string ls_Selected
long i
string ls_Uid
oleobject loo_Joined1
string ls_Response
oleobject loo_Joined2
string ls_Pattern
long li_Count
string ls_MessageId
string ls_ThreadId
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
loo_StatusText = create oleobject
li_rc = loo_StatusText.ConnectToNewObject("Chilkat.StringBuilder")
if li_rc < 0 then
destroy loo_StatusText
MessageBox("Error","Connecting to COM object failed")
return
end if
loo_StatusMatch = create oleobject
li_rc = loo_StatusMatch.ConnectToNewObject("Chilkat.JsonObject")
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
li_Success = loo_Token.LoadFile("gmail-mail-token.json")
if li_Success <> 1 then
Write-Debug "Could not load the protocol token from the private working directory."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
return
end if
if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
Write-Debug "Authorize or refresh the mailbox first."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
return
end if
ls_Mailbox = "user@example.com"
loo_Imap = create oleobject
li_rc = loo_Imap.ConnectToNewObject("Chilkat.Imap")
loo_Imap.Ssl = 1
loo_Imap.Port = 993
loo_Imap.RequireSslCertVerify = 1
loo_Imap.AuthMethod = "XOAUTH2"
li_Success = loo_Imap.Connect("imap.gmail.com")
if li_Success <> 1 then
Write-Debug "Could not establish the Gmail IMAP TLS connection."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
return
end if
li_Success = loo_Imap.Login(ls_Mailbox,loo_Token.StringOf("access_token"))
if li_Success <> 1 then
loo_Imap.Disconnect()
Write-Debug "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
return
end if
ls_Capabilities = loo_Imap.Capability()
if (loo_Imap.LastMethodSuccess <> 1) OR (loo_Imap.HasCapability("X-GM-EXT-1",ls_Capabilities) <> 1) then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Gmail IMAP extensions are unavailable."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
return
end if
loo_Folders = create oleobject
li_rc = loo_Folders.ConnectToNewObject("Chilkat.Mailboxes")
li_Success = loo_Imap.MbxList(0,"","*",loo_Folders)
if li_Success <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Could not list Gmail folders."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_Folders
return
end if
ls_AllMail = ""
li_FolderMatches = 0
f = 0
do while (f < loo_Folders.Count)
if (loo_Folders.HasFlag(f,"\All") = 1) AND (loo_Folders.IsSelectable(f) = 1) then
ls_AllMail = loo_Folders.GetName(f)
li_FolderMatches = li_FolderMatches + 1
end if
f = f + 1
loop
if li_FolderMatches <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Expected one selectable folder with the \All special-use attribute. Check label visibility."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_Folders
return
end if
loo_MailboxNames = create oleobject
li_rc = loo_MailboxNames.ConnectToNewObject("Chilkat.StringTable")
loo_MailboxNames.Append("INBOX")
loo_MailboxNames.Append(ls_AllMail)
loo_Unique = create oleobject
li_rc = loo_Unique.ConnectToNewObject("Chilkat.JsonObject")
loo_Found = create oleobject
li_rc = loo_Found.ConnectToNewObject("Chilkat.MessageSet")
loo_UidStrings = create oleobject
li_rc = loo_UidStrings.ConnectToNewObject("Chilkat.StringTable")
loo_Raw = create oleobject
li_rc = loo_Raw.ConnectToNewObject("Chilkat.StringBuilder")
loo_Captures = create oleobject
li_rc = loo_Captures.ConnectToNewObject("Chilkat.JsonObject")
li_FolderIndex = 0
do while (li_FolderIndex < loo_MailboxNames.Count)
ls_Selected = loo_MailboxNames.StringAt(li_FolderIndex)
li_Success = loo_Imap.ExamineMailbox(ls_Selected)
if li_Success <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Could not open the mailbox read-only."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_Folders
destroy loo_MailboxNames
destroy loo_Unique
destroy loo_Found
destroy loo_UidStrings
destroy loo_Raw
destroy loo_Captures
return
end if
li_Success = loo_Imap.QueryMbx("ALL",1,loo_Found)
if li_Success <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Could not obtain message UIDs."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_Folders
destroy loo_MailboxNames
destroy loo_Unique
destroy loo_Found
destroy loo_UidStrings
destroy loo_Raw
destroy loo_Captures
return
end if
loo_UidStrings.Clear()
if loo_Found.Count > 0 then
loo_UidStrings.SplitAndAppend(loo_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 < loo_UidStrings.Count) AND (i < 10))
ls_Uid = loo_UidStrings.StringAt(i)
loo_Joined1 = create oleobject
li_rc = loo_Joined1.ConnectToNewObject("Chilkat.StringBuilder")
loo_Joined1.Append("UID FETCH ")
loo_Joined1.Append(ls_Uid)
loo_Joined1.Append(" (UID X-GM-MSGID X-GM-THRID)")
ls_Response = loo_Imap.SendRawCommand(loo_Joined1.GetAsString())
loo_StatusText.SetString(ls_Response)
// A completed raw exchange can still return NO or BAD. Require tagged OK.
li_Completed = loo_StatusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",loo_StatusMatch,1000)
if (loo_Imap.LastMethodSuccess <> 1) OR (li_Completed <> 1) then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Could not fetch Gmail IDs."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_Folders
destroy loo_MailboxNames
destroy loo_Unique
destroy loo_Found
destroy loo_UidStrings
destroy loo_Raw
destroy loo_Captures
destroy loo_Joined1
return
end if
loo_Raw.SetString(ls_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.
loo_Joined2 = create oleobject
li_rc = loo_Joined2.ConnectToNewObject("Chilkat.StringBuilder")
loo_Joined2.Append("(?mi)^\* [0-9]+ FETCH \((?=[^\r\n]*\bUID ")
loo_Joined2.Append(ls_Uid)
loo_Joined2.Append("(?: |\)))(?=[^\r\n]*\bX-GM-MSGID ([0-9]+)(?: |\)))(?=[^\r\n]*\bX-GM-THRID ([0-9]+)(?: |\)))[^\r\n]*\)\r?$")
ls_Pattern = loo_Joined2.GetAsString()
li_Count = loo_Raw.RegexMatch(ls_Pattern,loo_Captures,1000)
if li_Count < 0 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Could not parse the Gmail metadata response."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_Folders
destroy loo_MailboxNames
destroy loo_Unique
destroy loo_Found
destroy loo_UidStrings
destroy loo_Raw
destroy loo_Captures
destroy loo_Joined1
destroy loo_Joined2
return
end if
if li_Count = 1 then
ls_MessageId = loo_Captures.StringOf("match[0].group[1].cap")
ls_ThreadId = loo_Captures.StringOf("match[0].group[2].cap")
if loo_Unique.IndexOf(ls_MessageId) < 0 then
// Direct JSON member names; both IDs remain strings without numeric conversion.
loo_Unique.AppendString(ls_MessageId,ls_ThreadId)
Write-Debug "Message ID: " + ls_MessageId + " Thread ID: " + ls_ThreadId
else
Write-Debug "Already encountered under another label: " + ls_MessageId
end if
else
Write-Debug "No single metadata row for UID " + ls_Uid + "; it may have disappeared. Skipping."
end if
i = i + 1
loop
li_FolderIndex = li_FolderIndex + 1
loop
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Unique sampled messages: " + string(loo_Unique.Size)
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_Folders
destroy loo_MailboxNames
destroy loo_Unique
destroy loo_Found
destroy loo_UidStrings
destroy loo_Raw
destroy loo_Captures
destroy loo_Joined1
destroy loo_Joined2