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 PHP ActiveX Downloads
<?php
$success = 0;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$statusText = new COM("Chilkat.StringBuilder");
$statusMatch = new COM("Chilkat.JsonObject");
$token = new COM("Chilkat.JsonObject");
$success = $token->LoadFile('gmail-mail-token.json');
if ($success != 1) {
print 'Could not load the protocol token from the private working directory.' . "\n";
exit;
}
if (($token->JsonTypeOf('access_token') != 1) or ($token->StringOfEquals('access_token','',1) == 1)) {
print 'Authorize or refresh the mailbox first.' . "\n";
exit;
}
$mailbox = 'user@example.com';
$imap = new COM("Chilkat.Imap");
$imap->Ssl = 1;
$imap->Port = 993;
$imap->RequireSslCertVerify = 1;
$imap->AuthMethod = 'XOAUTH2';
$success = $imap->Connect('imap.gmail.com');
if ($success != 1) {
print 'Could not establish the Gmail IMAP TLS connection.' . "\n";
exit;
}
$success = $imap->Login($mailbox,$token->stringOf('access_token'));
if ($success != 1) {
$imap->Disconnect();
print 'IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.' . "\n";
exit;
}
$capabilities = $imap->capability();
if (($imap->LastMethodSuccess != 1) or ($imap->HasCapability('X-GM-EXT-1',$capabilities) != 1)) {
$imap->Logout();
$imap->Disconnect();
print 'Gmail IMAP extensions are unavailable.' . "\n";
exit;
}
$folders = new COM("Chilkat.Mailboxes");
$success = $imap->MbxList(0,'','*',$folders);
if ($success != 1) {
$imap->Logout();
$imap->Disconnect();
print 'Could not list Gmail folders.' . "\n";
exit;
}
$allMail = '';
$folderMatches = 0;
$f = 0;
while (($f < $folders->Count)) {
if (($folders->HasFlag($f,'\\All') == 1) and ($folders->IsSelectable($f) == 1)) {
$allMail = $folders->getName($f);
$folderMatches = $folderMatches + 1;
}
$f = $f + 1;
}
if ($folderMatches != 1) {
$imap->Logout();
$imap->Disconnect();
print 'Expected one selectable folder with the \\All special-use attribute. Check label visibility.' . "\n";
exit;
}
$mailboxNames = new COM("Chilkat.StringTable");
$mailboxNames->Append('INBOX');
$mailboxNames->Append($allMail);
$unique = new COM("Chilkat.JsonObject");
$found = new COM("Chilkat.MessageSet");
$uidStrings = new COM("Chilkat.StringTable");
$raw = new COM("Chilkat.StringBuilder");
$captures = new COM("Chilkat.JsonObject");
$folderIndex = 0;
while (($folderIndex < $mailboxNames->Count)) {
$selected = $mailboxNames->stringAt($folderIndex);
$success = $imap->ExamineMailbox($selected);
if ($success != 1) {
$imap->Logout();
$imap->Disconnect();
print 'Could not open the mailbox read-only.' . "\n";
exit;
}
$success = $imap->QueryMbx('ALL',1,$found);
if ($success != 1) {
$imap->Logout();
$imap->Disconnect();
print 'Could not obtain message UIDs.' . "\n";
exit;
}
$uidStrings->Clear();
if ($found->Count > 0) {
$uidStrings->SplitAndAppend($found->toCommaSeparatedStr(),',',0,0);
}
// Sample up to 10 messages from each mailbox; this is not a complete synchronization.
$i = 0;
while ((($i < $uidStrings->Count) and ($i < 10))) {
$uid = $uidStrings->stringAt($i);
$joined1 = new COM("Chilkat.StringBuilder");
$joined1->Append('UID FETCH ');
$joined1->Append($uid);
$joined1->Append(' (UID X-GM-MSGID X-GM-THRID)');
$response = $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 != 1) or ($completed != 1)) {
$imap->Logout();
$imap->Disconnect();
print 'Could not fetch Gmail IDs.' . "\n";
exit;
}
$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.
$joined2 = new COM("Chilkat.StringBuilder");
$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?$');
$pattern = $joined2->getAsString();
$count = $raw->RegexMatch($pattern,$captures,1000);
if ($count < 0) {
$imap->Logout();
$imap->Disconnect();
print 'Could not parse the Gmail metadata response.' . "\n";
exit;
}
if ($count == 1) {
$messageId = $captures->stringOf('match[0].group[1].cap');
$threadId = $captures->stringOf('match[0].group[2].cap');
if ($unique->IndexOf($messageId) < 0) {
// Direct JSON member names; both IDs remain strings without numeric conversion.
$unique->AppendString($messageId,$threadId);
print 'Message ID: ' . $messageId . ' Thread ID: ' . $threadId . "\n";
}
else {
print 'Already encountered under another label: ' . $messageId . "\n";
}
}
else {
print 'No single metadata row for UID ' . $uid . '; it may have disappeared. Skipping.' . "\n";
}
$i = $i + 1;
}
$folderIndex = $folderIndex + 1;
}
$imap->Logout();
$imap->Disconnect();
print 'Unique sampled messages: ' . $unique->Size . "\n";
?>