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

C
#include <C_CkJsonObject.h>
#include <C_CkImap.h>
#include <C_CkMailboxes.h>
#include <C_CkStringBuilder.h>
#include <C_CkMessageSet.h>

void ChilkatSample(void)
    {
    BOOL success;
    int replacements;
    HCkJsonObject token;
    const char *mailbox;
    HCkImap imap;
    const char *capabilities;
    HCkMailboxes folders;
    const char *allMail;
    int folderMatches;
    int f;
    const char *query;
    HCkStringBuilder quoted;
    HCkStringBuilder joined1;
    const char *criteria;
    HCkMessageSet found;

    success = FALSE;

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

    token = CkJsonObject_Create();
    success = CkJsonObject_LoadFile(token,"gmail-mail-token.json");
    if (success != TRUE) {
        printf("Could not load the protocol token from the private working directory.\n");
        CkJsonObject_Dispose(token);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(token,"access_token") != 1) || (CkJsonObject_StringOfEquals(token,"access_token","",TRUE) == TRUE)) {
        printf("Authorize or refresh the mailbox first.\n");
        CkJsonObject_Dispose(token);
        return;
    }

    mailbox = "user@example.com";
    imap = CkImap_Create();
    CkImap_putSsl(imap,TRUE);
    CkImap_putPort(imap,993);
    CkImap_putRequireSslCertVerify(imap,TRUE);
    CkImap_putAuthMethod(imap,"XOAUTH2");
    success = CkImap_Connect(imap,"imap.gmail.com");
    if (success != TRUE) {
        printf("Could not establish the Gmail IMAP TLS connection.\n");
        CkJsonObject_Dispose(token);
        CkImap_Dispose(imap);
        return;
    }

    success = CkImap_Login(imap,mailbox,CkJsonObject_stringOf(token,"access_token"));
    if (success != TRUE) {
        CkImap_Disconnect(imap);
        printf("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.\n");
        CkJsonObject_Dispose(token);
        CkImap_Dispose(imap);
        return;
    }

    capabilities = CkImap_capability(imap);
    if ((CkImap_getLastMethodSuccess(imap) != TRUE) || (CkImap_HasCapability(imap,"X-GM-EXT-1",capabilities) != TRUE)) {
        CkImap_Logout(imap);
        CkImap_Disconnect(imap);
        printf("Gmail IMAP extensions are unavailable.\n");
        CkJsonObject_Dispose(token);
        CkImap_Dispose(imap);
        return;
    }

    folders = CkMailboxes_Create();
    success = CkImap_MbxList(imap,FALSE,"","*",folders);
    if (success != TRUE) {
        CkImap_Logout(imap);
        CkImap_Disconnect(imap);
        printf("Could not list Gmail folders.\n");
        CkJsonObject_Dispose(token);
        CkImap_Dispose(imap);
        CkMailboxes_Dispose(folders);
        return;
    }

    allMail = "";
    folderMatches = 0;
    f = 0;
    while ((f < CkMailboxes_getCount(folders))) {
        if ((CkMailboxes_HasFlag(folders,f,"\\All") == TRUE) && (CkMailboxes_IsSelectable(folders,f) == TRUE)) {
            allMail = CkMailboxes_getName(folders,f);
            folderMatches = folderMatches + 1;
        }

        f = f + 1;
    }

    if (folderMatches != 1) {
        CkImap_Logout(imap);
        CkImap_Disconnect(imap);
        printf("Expected one selectable folder with the \\All special-use attribute. Check label visibility.\n");
        CkJsonObject_Dispose(token);
        CkImap_Dispose(imap);
        CkMailboxes_Dispose(folders);
        return;
    }

    success = CkImap_ExamineMailbox(imap,allMail);
    if (success != TRUE) {
        CkImap_Logout(imap);
        CkImap_Disconnect(imap);
        printf("Could not open All Mail read-only.\n");
        CkJsonObject_Dispose(token);
        CkImap_Dispose(imap);
        CkMailboxes_Dispose(folders);
        return;
    }

    //  This search uses Gmail syntax inside a quoted IMAP search argument.
    query = "has:attachment from:sender@example.net";
    quoted = CkStringBuilder_Create();
    CkStringBuilder_Append(quoted,query);
    if ((CkStringBuilder_Contains(quoted,"\r",TRUE) == TRUE) || (CkStringBuilder_Contains(quoted,"\n",TRUE) == TRUE)) {
        CkImap_Logout(imap);
        CkImap_Disconnect(imap);
        printf("A search query must not contain CR or LF.\n");
        CkJsonObject_Dispose(token);
        CkImap_Dispose(imap);
        CkMailboxes_Dispose(folders);
        CkStringBuilder_Dispose(quoted);
        return;
    }

    replacements = CkStringBuilder_Replace(quoted,"\\","\\\\");
    replacements = CkStringBuilder_Replace(quoted,"\"","\\\"");
    joined1 = CkStringBuilder_Create();
    CkStringBuilder_Append(joined1,"X-GM-RAW \"");
    CkStringBuilder_Append(joined1,CkStringBuilder_getAsString(quoted));
    CkStringBuilder_Append(joined1,"\"");
    criteria = CkStringBuilder_getAsString(joined1);
    found = CkMessageSet_Create();
    success = CkImap_QueryMbx(imap,criteria,TRUE,found);
    if (success != TRUE) {
        CkImap_Logout(imap);
        CkImap_Disconnect(imap);
        printf("Gmail search failed.\n");
        CkJsonObject_Dispose(token);
        CkImap_Dispose(imap);
        CkMailboxes_Dispose(folders);
        CkStringBuilder_Dispose(quoted);
        CkStringBuilder_Dispose(joined1);
        CkMessageSet_Dispose(found);
        return;
    }

    //  Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
    printf("Matching messages: %d\n",CkMessageSet_getCount(found));
    printf("UID set: %s\n",CkMessageSet_toCompactString(found));
    CkImap_Logout(imap);
    CkImap_Disconnect(imap);


    CkJsonObject_Dispose(token);
    CkImap_Dispose(imap);
    CkMailboxes_Dispose(folders);
    CkStringBuilder_Dispose(quoted);
    CkStringBuilder_Dispose(joined1);
    CkMessageSet_Dispose(found);

    }