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

Perl
use strict;
use warnings;
use Chilkat2;

# Assumes Chilkat is unlocked. See Global Unlock Sample.

my $token = Chilkat2::JsonObject->new;
my $success = $token->LoadFile('gmail-mail-token.json');
if (!$success) {
    print "Could not load the protocol token from the private working directory.\n";
    exit;
}

if (($token->JsonTypeOf('access_token') != 1) || ($token->StringOfEquals('access_token', '', 1))) {
    print "Authorize or refresh the mailbox first.\n";
    exit;
}

my $mailbox = 'user@example.com';
my $imap = Chilkat2::Imap->new;
$imap->Ssl(1);
$imap->Port(993);
$imap->RequireSslCertVerify(1);
$imap->AuthMethod('XOAUTH2');
$success = $imap->Connect('imap.gmail.com');
if (!$success) {
    print "Could not establish the Gmail IMAP TLS connection.\n";
    exit;
}

$success = $imap->Login($mailbox, $token->StringOf('access_token'));
if (!$success) {
    $imap->Disconnect();
    print "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.\n";
    exit;
}

my $capabilities = $imap->Capability();
if ((!$imap->LastMethodSuccess) || (!$imap->HasCapability('X-GM-EXT-1', $capabilities))) {
    $imap->Logout();
    $imap->Disconnect();
    print "Gmail IMAP extensions are unavailable.\n";
    exit;
}

my $folders = Chilkat2::Mailboxes->new;
$success = $imap->MbxList(0, '', '*', $folders);
if (!$success) {
    $imap->Logout();
    $imap->Disconnect();
    print "Could not list Gmail folders.\n";
    exit;
}

my $allMail = '';
my $folderMatches = 0;
my $f = 0;
while ($f < $folders->Count) {
    if (($folders->HasFlag($f, '\All')) && ($folders->IsSelectable($f))) {
        $allMail = $folders->GetName($f);
        $folderMatches = $folderMatches + 1;
    }

    $f = $f + 1;
}

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

$success = $imap->ExamineMailbox($allMail);
if (!$success) {
    $imap->Logout();
    $imap->Disconnect();
    print "Could not open All Mail read-only.\n";
    exit;
}

# This search uses Gmail syntax inside a quoted IMAP search argument.
my $query = 'has:attachment from:sender@example.net';
my $quoted = Chilkat2::StringBuilder->new;
$quoted->Append($query);
if (($quoted->Contains("\r", 1)) || ($quoted->Contains("\n", 1))) {
    $imap->Logout();
    $imap->Disconnect();
    print "A search query must not contain CR or LF.\n";
    exit;
}

my $replacements = $quoted->Replace('\\', '\\\\');
$replacements = $quoted->Replace('"', '\"');
my $joined1 = Chilkat2::StringBuilder->new;
$joined1->Append('X-GM-RAW "');
$joined1->Append($quoted->GetAsString());
$joined1->Append('"');
my $criteria = $joined1->GetAsString();
my $found = Chilkat2::MessageSet->new;
$success = $imap->QueryMbx($criteria, 1, $found);
if (!$success) {
    $imap->Logout();
    $imap->Disconnect();
    print "Gmail search failed.\n";
    exit;
}

# Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
print 'Matching messages: ', $found->Count, "\n";
print 'UID set: ', $found->ToCompactString(), "\n";
$imap->Logout();
$imap->Disconnect();