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

Gmail IMAP: Search with Gmail Search Syntax

See more GMail SMTP/IMAP/POP Examples

Search with Gmail operators through X-GM-RAW, using QueryMbx to obtain UIDs. The example discovers All Mail and opens it read-only. It quotes the query for the IMAP command rather than URL-encoding it.

IMAP search is limited to the selected mailbox. All Mail normally covers inbox and archived messages, but excludes Spam and Trash; a Gmail search operator cannot expand an IMAP search beyond its selected mailbox. An empty result is successful. Returned IMAP UIDs are mailbox-specific and are not Gmail message IDs. Persist them only with their mailbox and UIDVALIDITY.

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 <CkJsonObjectW.h>
#include <CkImapW.h>
#include <CkMailboxesW.h>
#include <CkStringBuilderW.h>
#include <CkMessageSetW.h>

void ChilkatSample(void)
    {
    bool success = false;

    int replacements;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkJsonObjectW token;
    success = token.LoadFile(L"gmail-mail-token.json");
    if (success != true) {
        wprintf(L"Could not load the protocol token from the private working directory.\n");
        return;
    }

    if ((token.JsonTypeOf(L"access_token") != 1) || (token.StringOfEquals(L"access_token",L"",true) == true)) {
        wprintf(L"Authorize or refresh the mailbox first.\n");
        return;
    }

    const wchar_t *mailbox = L"user@example.com";
    CkImapW imap;
    imap.put_Ssl(true);
    imap.put_Port(993);
    imap.put_RequireSslCertVerify(true);
    imap.put_AuthMethod(L"XOAUTH2");
    success = imap.Connect(L"imap.gmail.com");
    if (success != true) {
        wprintf(L"Could not establish the Gmail IMAP TLS connection.\n");
        return;
    }

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

    const wchar_t *capabilities = imap.capability();
    if ((imap.get_LastMethodSuccess() != true) || (imap.HasCapability(L"X-GM-EXT-1",capabilities) != true)) {
        imap.Logout();
        imap.Disconnect();
        wprintf(L"Gmail IMAP extensions are unavailable.\n");
        return;
    }

    CkMailboxesW folders;
    success = imap.MbxList(false,L"",L"*",folders);
    if (success != true) {
        imap.Logout();
        imap.Disconnect();
        wprintf(L"Could not list Gmail folders.\n");
        return;
    }

    const wchar_t *allMail = L"";
    int folderMatches = 0;
    int f = 0;
    while ((f < folders.get_Count())) {
        if ((folders.HasFlag(f,L"\\All") == true) && (folders.IsSelectable(f) == true)) {
            allMail = folders.getName(f);
            folderMatches = folderMatches + 1;
        }

        f = f + 1;
    }

    if (folderMatches != 1) {
        imap.Logout();
        imap.Disconnect();
        wprintf(L"Expected one selectable folder with the \\All special-use attribute. Check label visibility.\n");
        return;
    }

    success = imap.ExamineMailbox(allMail);
    if (success != true) {
        imap.Logout();
        imap.Disconnect();
        wprintf(L"Could not open All Mail read-only.\n");
        return;
    }

    //  This search uses Gmail syntax inside a quoted IMAP search argument.
    const wchar_t *query = L"has:attachment from:sender@example.net";
    CkStringBuilderW quoted;
    quoted.Append(query);
    if ((quoted.Contains(L"\r",true) == true) || (quoted.Contains(L"\n",true) == true)) {
        imap.Logout();
        imap.Disconnect();
        wprintf(L"A search query must not contain CR or LF.\n");
        return;
    }

    replacements = quoted.Replace(L"\\",L"\\\\");
    replacements = quoted.Replace(L"\"",L"\\\"");
    CkStringBuilderW joined1;
    joined1.Append(L"X-GM-RAW \"");
    joined1.Append(quoted.getAsString());
    joined1.Append(L"\"");
    const wchar_t *criteria = joined1.getAsString();
    CkMessageSetW found;
    success = imap.QueryMbx(criteria,true,found);
    if (success != true) {
        imap.Logout();
        imap.Disconnect();
        wprintf(L"Gmail search failed.\n");
        return;
    }

    //  Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
    wprintf(L"Matching messages: %d\n",found.get_Count());
    wprintf(L"UID set: %s\n",found.toCompactString());
    imap.Logout();
    imap.Disconnect();
    }