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 Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local statusText = chilkat.StringBuilder.new()
local statusMatch = chilkat.JsonObject.new()
local completed = 0
local token = chilkat.JsonObject.new()
local success = token:load_file("gmail-mail-token.json")
if not success then
print("Could not load the protocol token from the private working directory.")
return
end
if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
print("Authorize or refresh the mailbox first.")
return
end
local mailbox = "user@example.com"
local imap = chilkat.Imap.new()
imap.ssl = true
imap.port = 993
imap.require_ssl_cert_verify = true
imap.auth_method = "XOAUTH2"
success = imap:connect("imap.gmail.com")
if not success then
print("Could not establish the Gmail IMAP TLS connection.")
return
end
success = imap:login(mailbox, token:string_of("access_token"))
if not success then
imap:disconnect()
print("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
return
end
local capabilities = imap:capability()
if (not imap.last_method_success) or (not imap:has_capability("X-GM-EXT-1", capabilities)) then
imap:logout()
imap:disconnect()
print("Gmail IMAP extensions are unavailable.")
return
end
local folders = chilkat.Mailboxes.new()
success = imap:mbx_list(false, "", "*", folders)
if not success then
imap:logout()
imap:disconnect()
print("Could not list Gmail folders.")
return
end
local allMail = ""
local folderMatches = 0
local f = 0
while f < folders.count do
if (folders:has_flag(f, "\\All")) and (folders:is_selectable(f)) then
allMail = folders:get_name(f)
folderMatches = folderMatches + 1
end
f = f + 1
end
if folderMatches ~= 1 then
imap:logout()
imap:disconnect()
print("Expected one selectable folder with the \\All special-use attribute. Check label visibility.")
return
end
local mailboxNames = chilkat.StringTable.new()
mailboxNames:append("INBOX")
mailboxNames:append(allMail)
local unique = chilkat.JsonObject.new()
local found = chilkat.MessageSet.new()
local uidStrings = chilkat.StringTable.new()
local raw = chilkat.StringBuilder.new()
local captures = chilkat.JsonObject.new()
local folderIndex = 0
while folderIndex < mailboxNames.count do
local selected = mailboxNames:string_at(folderIndex)
success = imap:examine_mailbox(selected)
if not success then
imap:logout()
imap:disconnect()
print("Could not open the mailbox read-only.")
return
end
success = imap:query_mbx("ALL", true, found)
if not success then
imap:logout()
imap:disconnect()
print("Could not obtain message UIDs.")
return
end
uidStrings:clear()
if found.count > 0 then
uidStrings:split_and_append(found:to_comma_separated_str(), ",", false, false)
end
-- Sample up to 10 messages from each mailbox; this is not a complete synchronization.
local i = 0
while (i < uidStrings.count) and (i < 10) do
local uid = uidStrings:string_at(i)
local joined1 = chilkat.StringBuilder.new()
joined1:append("UID FETCH ")
joined1:append(uid)
joined1:append(" (UID X-GM-MSGID X-GM-THRID)")
local response = imap:send_raw_command(joined1:get_as_string())
statusText:set_string(response)
-- A completed raw exchange can still return NO or BAD. Require tagged OK.
completed = statusText:regex_match("(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z", statusMatch, 1000)
if (not imap.last_method_success) or (completed ~= 1) then
imap:logout()
imap:disconnect()
print("Could not fetch Gmail IDs.")
return
end
raw:set_string(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.
local joined2 = chilkat.StringBuilder.new()
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?$")
local pattern = joined2:get_as_string()
local count = raw:regex_match(pattern, captures, 1000)
if count < 0 then
imap:logout()
imap:disconnect()
print("Could not parse the Gmail metadata response.")
return
end
if count == 1 then
local messageId = captures:string_of("match[0].group[1].cap")
local threadId = captures:string_of("match[0].group[2].cap")
if unique:index_of(messageId) < 0 then
-- Direct JSON member names; both IDs remain strings without numeric conversion.
unique:append_string(messageId, threadId)
print("Message ID: " .. messageId .. " Thread ID: " .. threadId)
else
print("Already encountered under another label: " .. messageId)
end
else
print("No single metadata row for UID " .. uid .. "; it may have disappeared. Skipping.")
end
i = i + 1
end
folderIndex = folderIndex + 1
end
imap:logout()
imap:disconnect()
print("Unique sampled messages: " .. unique.size)