Sample code for 30+ languages & platforms
C++ Requires Chilkat v11.1.0+

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.

Google documentation

Chilkat C++ Downloads

C++
#include <CkStringBuilder.h>
#include <CkJsonObject.h>
#include <CkImap.h>
#include <CkMailboxes.h>
#include <CkStringTable.h>
#include <CkMessageSet.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkStringBuilder statusText;
    CkJsonObject statusMatch;
    int completed;
    CkJsonObject token;
    success = token.LoadFile("gmail-mail-token.json");
    if (success != true) {
        std::cout << "Could not load the protocol token from the private working directory." << "\r\n";
        return;
    }

    if ((token.JsonTypeOf("access_token") != 1) || (token.StringOfEquals("access_token","",true) == true)) {
        std::cout << "Authorize or refresh the mailbox first." << "\r\n";
        return;
    }

    const char *mailbox = "user@example.com";
    CkImap imap;
    imap.put_Ssl(true);
    imap.put_Port(993);
    imap.put_RequireSslCertVerify(true);
    imap.put_AuthMethod("XOAUTH2");
    success = imap.Connect("imap.gmail.com");
    if (success != true) {
        std::cout << "Could not establish the Gmail IMAP TLS connection." << "\r\n";
        return;
    }

    success = imap.Login(mailbox,token.stringOf("access_token"));
    if (success != true) {
        imap.Disconnect();
        std::cout << "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy." << "\r\n";
        return;
    }

    const char *capabilities = imap.capability();
    if ((imap.get_LastMethodSuccess() != true) || (imap.HasCapability("X-GM-EXT-1",capabilities) != true)) {
        imap.Logout();
        imap.Disconnect();
        std::cout << "Gmail IMAP extensions are unavailable." << "\r\n";
        return;
    }

    CkMailboxes folders;
    success = imap.MbxList(false,"","*",folders);
    if (success != true) {
        imap.Logout();
        imap.Disconnect();
        std::cout << "Could not list Gmail folders." << "\r\n";
        return;
    }

    const char *allMail = "";
    int folderMatches = 0;
    int f = 0;
    while ((f < folders.get_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();
        std::cout << "Expected one selectable folder with the \\All special-use attribute. Check label visibility." << "\r\n";
        return;
    }

    CkStringTable mailboxNames;
    mailboxNames.Append("INBOX");
    mailboxNames.Append(allMail);
    CkJsonObject unique;
    CkMessageSet found;
    CkStringTable uidStrings;
    CkStringBuilder raw;
    CkJsonObject captures;
    int folderIndex = 0;
    while ((folderIndex < mailboxNames.get_Count())) {
        const char *selected = mailboxNames.stringAt(folderIndex);
        success = imap.ExamineMailbox(selected);
        if (success != true) {
            imap.Logout();
            imap.Disconnect();
            std::cout << "Could not open the mailbox read-only." << "\r\n";
            return;
        }

        success = imap.QueryMbx("ALL",true,found);
        if (success != true) {
            imap.Logout();
            imap.Disconnect();
            std::cout << "Could not obtain message UIDs." << "\r\n";
            return;
        }

        uidStrings.Clear();
        if (found.get_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.get_Count()) && (i < 10))) {
            const char *uid = uidStrings.stringAt(i);
            CkStringBuilder joined1;
            joined1.Append("UID FETCH ");
            joined1.Append(uid);
            joined1.Append(" (UID X-GM-MSGID X-GM-THRID)");
            const char *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.get_LastMethodSuccess() != true) || (completed != 1)) {
                imap.Logout();
                imap.Disconnect();
                std::cout << "Could not fetch Gmail IDs." << "\r\n";
                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.
            CkStringBuilder joined2;
            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?$");
            const char *pattern = joined2.getAsString();
            int count = raw.RegexMatch(pattern,captures,1000);
            if (count < 0) {
                imap.Logout();
                imap.Disconnect();
                std::cout << "Could not parse the Gmail metadata response." << "\r\n";
                return;
            }

            if (count == 1) {
                const char *messageId = captures.stringOf("match[0].group[1].cap");
                const char *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);
                    std::cout << "Message ID: " << messageId << "  Thread ID: " << threadId << "\r\n";
                }
                else {
                    std::cout << "Already encountered under another label: " << messageId << "\r\n";
                }

            }
            else {
                std::cout << "No single metadata row for UID " << uid << "; it may have disappeared. Skipping." << "\r\n";
            }

            i = i + 1;
        }

        folderIndex = folderIndex + 1;
    }

    imap.Logout();
    imap.Disconnect();
    std::cout << "Unique sampled messages: " << unique.get_Size() << "\r\n";
    }