Sample code for 30+ languages & platforms
Unicode 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 Unicode C Downloads

Unicode C
#include <C_CkStringBuilderW.h>
#include <C_CkJsonObjectW.h>
#include <C_CkImapW.h>
#include <C_CkMailboxesW.h>
#include <C_CkStringTableW.h>
#include <C_CkMessageSetW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkStringBuilderW statusText;
    HCkJsonObjectW statusMatch;
    int completed;
    HCkJsonObjectW token;
    const wchar_t *mailbox;
    HCkImapW imap;
    const wchar_t *capabilities;
    HCkMailboxesW folders;
    const wchar_t *allMail;
    int folderMatches;
    int f;
    HCkStringTableW mailboxNames;
    HCkJsonObjectW unique;
    HCkMessageSetW found;
    HCkStringTableW uidStrings;
    HCkStringBuilderW raw;
    HCkJsonObjectW captures;
    int folderIndex;
    const wchar_t *selected;
    int i;
    const wchar_t *uid;
    HCkStringBuilderW joined1;
    const wchar_t *response;
    HCkStringBuilderW joined2;
    const wchar_t *pattern;
    int count;
    const wchar_t *messageId;
    const wchar_t *threadId;

    success = FALSE;

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

    statusText = CkStringBuilderW_Create();
    statusMatch = CkJsonObjectW_Create();

    token = CkJsonObjectW_Create();
    success = CkJsonObjectW_LoadFile(token,L"gmail-mail-token.json");
    if (success != TRUE) {
        wprintf(L"Could not load the protocol token from the private working directory.\n");
        CkStringBuilderW_Dispose(statusText);
        CkJsonObjectW_Dispose(statusMatch);
        CkJsonObjectW_Dispose(token);
        return;
    }

    if ((CkJsonObjectW_JsonTypeOf(token,L"access_token") != 1) || (CkJsonObjectW_StringOfEquals(token,L"access_token",L"",TRUE) == TRUE)) {
        wprintf(L"Authorize or refresh the mailbox first.\n");
        CkStringBuilderW_Dispose(statusText);
        CkJsonObjectW_Dispose(statusMatch);
        CkJsonObjectW_Dispose(token);
        return;
    }

    mailbox = L"user@example.com";
    imap = CkImapW_Create();
    CkImapW_putSsl(imap,TRUE);
    CkImapW_putPort(imap,993);
    CkImapW_putRequireSslCertVerify(imap,TRUE);
    CkImapW_putAuthMethod(imap,L"XOAUTH2");
    success = CkImapW_Connect(imap,L"imap.gmail.com");
    if (success != TRUE) {
        wprintf(L"Could not establish the Gmail IMAP TLS connection.\n");
        CkStringBuilderW_Dispose(statusText);
        CkJsonObjectW_Dispose(statusMatch);
        CkJsonObjectW_Dispose(token);
        CkImapW_Dispose(imap);
        return;
    }

    success = CkImapW_Login(imap,mailbox,CkJsonObjectW_stringOf(token,L"access_token"));
    if (success != TRUE) {
        CkImapW_Disconnect(imap);
        wprintf(L"IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.\n");
        CkStringBuilderW_Dispose(statusText);
        CkJsonObjectW_Dispose(statusMatch);
        CkJsonObjectW_Dispose(token);
        CkImapW_Dispose(imap);
        return;
    }

    capabilities = CkImapW_capability(imap);
    if ((CkImapW_getLastMethodSuccess(imap) != TRUE) || (CkImapW_HasCapability(imap,L"X-GM-EXT-1",capabilities) != TRUE)) {
        CkImapW_Logout(imap);
        CkImapW_Disconnect(imap);
        wprintf(L"Gmail IMAP extensions are unavailable.\n");
        CkStringBuilderW_Dispose(statusText);
        CkJsonObjectW_Dispose(statusMatch);
        CkJsonObjectW_Dispose(token);
        CkImapW_Dispose(imap);
        return;
    }

    folders = CkMailboxesW_Create();
    success = CkImapW_MbxList(imap,FALSE,L"",L"*",folders);
    if (success != TRUE) {
        CkImapW_Logout(imap);
        CkImapW_Disconnect(imap);
        wprintf(L"Could not list Gmail folders.\n");
        CkStringBuilderW_Dispose(statusText);
        CkJsonObjectW_Dispose(statusMatch);
        CkJsonObjectW_Dispose(token);
        CkImapW_Dispose(imap);
        CkMailboxesW_Dispose(folders);
        return;
    }

    allMail = L"";
    folderMatches = 0;
    f = 0;
    while ((f < CkMailboxesW_getCount(folders))) {
        if ((CkMailboxesW_HasFlag(folders,f,L"\\All") == TRUE) && (CkMailboxesW_IsSelectable(folders,f) == TRUE)) {
            allMail = CkMailboxesW_getName(folders,f);
            folderMatches = folderMatches + 1;
        }

        f = f + 1;
    }

    if (folderMatches != 1) {
        CkImapW_Logout(imap);
        CkImapW_Disconnect(imap);
        wprintf(L"Expected one selectable folder with the \\All special-use attribute. Check label visibility.\n");
        CkStringBuilderW_Dispose(statusText);
        CkJsonObjectW_Dispose(statusMatch);
        CkJsonObjectW_Dispose(token);
        CkImapW_Dispose(imap);
        CkMailboxesW_Dispose(folders);
        return;
    }

    mailboxNames = CkStringTableW_Create();
    CkStringTableW_Append(mailboxNames,L"INBOX");
    CkStringTableW_Append(mailboxNames,allMail);
    unique = CkJsonObjectW_Create();
    found = CkMessageSetW_Create();
    uidStrings = CkStringTableW_Create();
    raw = CkStringBuilderW_Create();
    captures = CkJsonObjectW_Create();
    folderIndex = 0;
    while ((folderIndex < CkStringTableW_getCount(mailboxNames))) {
        selected = CkStringTableW_stringAt(mailboxNames,folderIndex);
        success = CkImapW_ExamineMailbox(imap,selected);
        if (success != TRUE) {
            CkImapW_Logout(imap);
            CkImapW_Disconnect(imap);
            wprintf(L"Could not open the mailbox read-only.\n");
            CkStringBuilderW_Dispose(statusText);
            CkJsonObjectW_Dispose(statusMatch);
            CkJsonObjectW_Dispose(token);
            CkImapW_Dispose(imap);
            CkMailboxesW_Dispose(folders);
            CkStringTableW_Dispose(mailboxNames);
            CkJsonObjectW_Dispose(unique);
            CkMessageSetW_Dispose(found);
            CkStringTableW_Dispose(uidStrings);
            CkStringBuilderW_Dispose(raw);
            CkJsonObjectW_Dispose(captures);
            return;
        }

        success = CkImapW_QueryMbx(imap,L"ALL",TRUE,found);
        if (success != TRUE) {
            CkImapW_Logout(imap);
            CkImapW_Disconnect(imap);
            wprintf(L"Could not obtain message UIDs.\n");
            CkStringBuilderW_Dispose(statusText);
            CkJsonObjectW_Dispose(statusMatch);
            CkJsonObjectW_Dispose(token);
            CkImapW_Dispose(imap);
            CkMailboxesW_Dispose(folders);
            CkStringTableW_Dispose(mailboxNames);
            CkJsonObjectW_Dispose(unique);
            CkMessageSetW_Dispose(found);
            CkStringTableW_Dispose(uidStrings);
            CkStringBuilderW_Dispose(raw);
            CkJsonObjectW_Dispose(captures);
            return;
        }

        CkStringTableW_Clear(uidStrings);
        if (CkMessageSetW_getCount(found) > 0) {
            CkStringTableW_SplitAndAppend(uidStrings,CkMessageSetW_toCommaSeparatedStr(found),L",",FALSE,FALSE);
        }

        //  Sample up to 10 messages from each mailbox; this is not a complete synchronization.
        i = 0;
        while (((i < CkStringTableW_getCount(uidStrings)) && (i < 10))) {
            uid = CkStringTableW_stringAt(uidStrings,i);
            joined1 = CkStringBuilderW_Create();
            CkStringBuilderW_Append(joined1,L"UID FETCH ");
            CkStringBuilderW_Append(joined1,uid);
            CkStringBuilderW_Append(joined1,L" (UID X-GM-MSGID X-GM-THRID)");
            response = CkImapW_sendRawCommand(imap,CkStringBuilderW_getAsString(joined1));
            CkStringBuilderW_SetString(statusText,response);
            //  A completed raw exchange can still return NO or BAD. Require tagged OK.
            completed = CkStringBuilderW_RegexMatch(statusText,L"(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z",statusMatch,1000);

            if ((CkImapW_getLastMethodSuccess(imap) != TRUE) || (completed != 1)) {
                CkImapW_Logout(imap);
                CkImapW_Disconnect(imap);
                wprintf(L"Could not fetch Gmail IDs.\n");
                CkStringBuilderW_Dispose(statusText);
                CkJsonObjectW_Dispose(statusMatch);
                CkJsonObjectW_Dispose(token);
                CkImapW_Dispose(imap);
                CkMailboxesW_Dispose(folders);
                CkStringTableW_Dispose(mailboxNames);
                CkJsonObjectW_Dispose(unique);
                CkMessageSetW_Dispose(found);
                CkStringTableW_Dispose(uidStrings);
                CkStringBuilderW_Dispose(raw);
                CkJsonObjectW_Dispose(captures);
                CkStringBuilderW_Dispose(joined1);
                return;
            }

            CkStringBuilderW_SetString(raw,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 = CkStringBuilderW_Create();
            CkStringBuilderW_Append(joined2,L"(?mi)^\\* [0-9]+ FETCH \\((?=[^\\r\\n]*\\bUID ");
            CkStringBuilderW_Append(joined2,uid);
            CkStringBuilderW_Append(joined2,L"(?: |\\)))(?=[^\\r\\n]*\\bX-GM-MSGID ([0-9]+)(?: |\\)))(?=[^\\r\\n]*\\bX-GM-THRID ([0-9]+)(?: |\\)))[^\\r\\n]*\\)\\r?$");
            pattern = CkStringBuilderW_getAsString(joined2);
            count = CkStringBuilderW_RegexMatch(raw,pattern,captures,1000);
            if (count < 0) {
                CkImapW_Logout(imap);
                CkImapW_Disconnect(imap);
                wprintf(L"Could not parse the Gmail metadata response.\n");
                CkStringBuilderW_Dispose(statusText);
                CkJsonObjectW_Dispose(statusMatch);
                CkJsonObjectW_Dispose(token);
                CkImapW_Dispose(imap);
                CkMailboxesW_Dispose(folders);
                CkStringTableW_Dispose(mailboxNames);
                CkJsonObjectW_Dispose(unique);
                CkMessageSetW_Dispose(found);
                CkStringTableW_Dispose(uidStrings);
                CkStringBuilderW_Dispose(raw);
                CkJsonObjectW_Dispose(captures);
                CkStringBuilderW_Dispose(joined1);
                CkStringBuilderW_Dispose(joined2);
                return;
            }

            if (count == 1) {
                messageId = CkJsonObjectW_stringOf(captures,L"match[0].group[1].cap");
                threadId = CkJsonObjectW_stringOf(captures,L"match[0].group[2].cap");
                if (CkJsonObjectW_IndexOf(unique,messageId) < 0) {
                    //  Direct JSON member names; both IDs remain strings without numeric conversion.
                    CkJsonObjectW_AppendString(unique,messageId,threadId);
                    wprintf(L"Message ID: %s  Thread ID: %s\n",messageId,threadId);
                }
                else {
                    wprintf(L"Already encountered under another label: %s\n",messageId);
                }

            }
            else {
                wprintf(L"No single metadata row for UID %s; it may have disappeared. Skipping.\n",uid);
            }

            i = i + 1;
        }

        folderIndex = folderIndex + 1;
    }

    CkImapW_Logout(imap);
    CkImapW_Disconnect(imap);
    wprintf(L"Unique sampled messages: %d\n",CkJsonObjectW_getSize(unique));


    CkStringBuilderW_Dispose(statusText);
    CkJsonObjectW_Dispose(statusMatch);
    CkJsonObjectW_Dispose(token);
    CkImapW_Dispose(imap);
    CkMailboxesW_Dispose(folders);
    CkStringTableW_Dispose(mailboxNames);
    CkJsonObjectW_Dispose(unique);
    CkMessageSetW_Dispose(found);
    CkStringTableW_Dispose(uidStrings);
    CkStringBuilderW_Dispose(raw);
    CkJsonObjectW_Dispose(captures);
    CkStringBuilderW_Dispose(joined1);
    CkStringBuilderW_Dispose(joined2);

    }