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 Delphi DLL Downloads
var
success: Boolean;
replacements: Integer;
token: HCkJsonObject;
mailbox: PWideChar;
imap: HCkImap;
capabilities: PWideChar;
folders: HCkMailboxes;
allMail: PWideChar;
folderMatches: Integer;
f: Integer;
query: PWideChar;
quoted: HCkStringBuilder;
joined1: HCkStringBuilder;
criteria: PWideChar;
found: HCkMessageSet;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
token := CkJsonObject_Create();
success := CkJsonObject_LoadFile(token,'gmail-mail-token.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load the protocol token from the private working directory.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (CkJsonObject_StringOfEquals(token,'access_token','',True) = True)) then
begin
Memo1.Lines.Add('Authorize or refresh the mailbox first.');
Exit;
end;
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) then
begin
Memo1.Lines.Add('Could not establish the Gmail IMAP TLS connection.');
Exit;
end;
success := CkImap_Login(imap,mailbox,CkJsonObject__stringOf(token,'access_token'));
if (success <> True) then
begin
CkImap_Disconnect(imap);
Memo1.Lines.Add('IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.');
Exit;
end;
capabilities := CkImap__capability(imap);
if ((CkImap_getLastMethodSuccess(imap) <> True) or (CkImap_HasCapability(imap,'X-GM-EXT-1',capabilities) <> True)) then
begin
CkImap_Logout(imap);
CkImap_Disconnect(imap);
Memo1.Lines.Add('Gmail IMAP extensions are unavailable.');
Exit;
end;
folders := CkMailboxes_Create();
success := CkImap_MbxList(imap,False,'','*',folders);
if (success <> True) then
begin
CkImap_Logout(imap);
CkImap_Disconnect(imap);
Memo1.Lines.Add('Could not list Gmail folders.');
Exit;
end;
allMail := '';
folderMatches := 0;
f := 0;
while (f < CkMailboxes_getCount(folders)) do
begin
if ((CkMailboxes_HasFlag(folders,f,'\All') = True) and (CkMailboxes_IsSelectable(folders,f) = True)) then
begin
allMail := CkMailboxes__getName(folders,f);
folderMatches := folderMatches + 1;
end;
f := f + 1;
end;
if (folderMatches <> 1) then
begin
CkImap_Logout(imap);
CkImap_Disconnect(imap);
Memo1.Lines.Add('Expected one selectable folder with the \All special-use attribute. Check label visibility.');
Exit;
end;
success := CkImap_ExamineMailbox(imap,allMail);
if (success <> True) then
begin
CkImap_Logout(imap);
CkImap_Disconnect(imap);
Memo1.Lines.Add('Could not open All Mail read-only.');
Exit;
end;
// 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,#13,True) = True) or (CkStringBuilder_Contains(quoted,#10,True) = True)) then
begin
CkImap_Logout(imap);
CkImap_Disconnect(imap);
Memo1.Lines.Add('A search query must not contain CR or LF.');
Exit;
end;
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) then
begin
CkImap_Logout(imap);
CkImap_Disconnect(imap);
Memo1.Lines.Add('Gmail search failed.');
Exit;
end;
// Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
Memo1.Lines.Add('Matching messages: ' + IntToStr(CkMessageSet_getCount(found)));
Memo1.Lines.Add('UID set: ' + 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);