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.
Chilkat PHP Downloads
<?php
use Chilkat2\Imap;
use Chilkat2\JsonObject;
use Chilkat2\Mailboxes;
use Chilkat2\MessageSet;
use Chilkat2\StringBuilder;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$token = new JsonObject();
try {
$token->LoadFile('gmail-mail-token.json');
} catch (\Chilkat2\Exception $e) {
echo "Could not load the protocol token from the private working directory.\n";
exit;
}
if (($token->JsonTypeOf('access_token') != 1) || ($token->StringOfEquals('access_token', '', true))) {
echo "Authorize or refresh the mailbox first.\n";
exit;
}
$mailbox = 'user@example.com';
$imap = new Imap();
$imap->Ssl = true;
$imap->Port = 993;
$imap->RequireSslCertVerify = true;
$imap->AuthMethod = 'XOAUTH2';
try {
$imap->Connect('imap.gmail.com');
} catch (\Chilkat2\Exception $e) {
echo "Could not establish the Gmail IMAP TLS connection.\n";
exit;
}
try {
$imap->Login($mailbox, $token->StringOf('access_token'));
} catch (\Chilkat2\Exception $e) {
$imap->Disconnect();
echo "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.\n";
exit;
}
$capabilities = $imap->Capability();
if ((!$imap->LastMethodSuccess) || (!$imap->HasCapability('X-GM-EXT-1', $capabilities))) {
$imap->Logout();
$imap->Disconnect();
echo "Gmail IMAP extensions are unavailable.\n";
exit;
}
$folders = new Mailboxes();
try {
$imap->MbxList(false, '', '*', $folders);
} catch (\Chilkat2\Exception $e) {
$imap->Logout();
$imap->Disconnect();
echo "Could not list Gmail folders.\n";
exit;
}
$allMail = '';
$folderMatches = 0;
$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();
echo "Expected one selectable folder with the \\All special-use attribute. Check label visibility.\n";
exit;
}
try {
$imap->ExamineMailbox($allMail);
} catch (\Chilkat2\Exception $e) {
$imap->Logout();
$imap->Disconnect();
echo "Could not open All Mail read-only.\n";
exit;
}
// This search uses Gmail syntax inside a quoted IMAP search argument.
$query = 'has:attachment from:sender@example.net';
$quoted = new StringBuilder();
$quoted->Append($query);
if (($quoted->Contains("\r", true)) || ($quoted->Contains("\n", true))) {
$imap->Logout();
$imap->Disconnect();
echo "A search query must not contain CR or LF.\n";
exit;
}
$replacements = $quoted->Replace('\\', '\\\\');
$replacements = $quoted->Replace('"', '\"');
$joined1 = new StringBuilder();
$joined1->Append('X-GM-RAW "');
$joined1->Append($quoted->GetAsString());
$joined1->Append('"');
$criteria = $joined1->GetAsString();
$found = new MessageSet();
try {
$imap->QueryMbx($criteria, true, $found);
} catch (\Chilkat2\Exception $e) {
$imap->Logout();
$imap->Disconnect();
echo "Gmail search failed.\n";
exit;
}
// Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
echo 'Matching messages: ', $found->Count, "\n";
echo 'UID set: ', $found->ToCompactString(), "\n";
$imap->Logout();
$imap->Disconnect();