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