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 ActiveX Downloads
var
success: Integer;
replacements: Integer;
token: TChilkatJsonObject;
mailbox: WideString;
imap: TChilkatImap;
capabilities: WideString;
folders: TMailboxes;
allMail: WideString;
folderMatches: Integer;
f: Integer;
query: WideString;
quoted: TChilkatStringBuilder;
joined1: TChilkatStringBuilder;
criteria: WideString;
found: TMessageSet;
begin
success := 0;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
token := TChilkatJsonObject.Create(Self);
success := token.LoadFile('gmail-mail-token.json');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not load the protocol token from the private working directory.');
Exit;
end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',1) = 1)) then
begin
Memo1.Lines.Add('Authorize or refresh the mailbox first.');
Exit;
end;
mailbox := 'user@example.com';
imap := TChilkatImap.Create(Self);
imap.Ssl := 1;
imap.Port := 993;
imap.RequireSslCertVerify := 1;
imap.AuthMethod := 'XOAUTH2';
success := imap.Connect('imap.gmail.com');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not establish the Gmail IMAP TLS connection.');
Exit;
end;
success := imap.Login(mailbox,token.StringOf('access_token'));
if (success <> 1) then
begin
imap.Disconnect();
Memo1.Lines.Add('IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.');
Exit;
end;
capabilities := imap.Capability();
if ((imap.LastMethodSuccess <> 1) or (imap.HasCapability('X-GM-EXT-1',capabilities) <> 1)) then
begin
imap.Logout();
imap.Disconnect();
Memo1.Lines.Add('Gmail IMAP extensions are unavailable.');
Exit;
end;
folders := TMailboxes.Create(Self);
success := imap.MbxList(0,'','*',folders.ControlInterface);
if (success <> 1) then
begin
imap.Logout();
imap.Disconnect();
Memo1.Lines.Add('Could not list Gmail folders.');
Exit;
end;
allMail := '';
folderMatches := 0;
f := 0;
while (f < folders.Count) do
begin
if ((folders.HasFlag(f,'\All') = 1) and (folders.IsSelectable(f) = 1)) then
begin
allMail := folders.GetName(f);
folderMatches := folderMatches + 1;
end;
f := f + 1;
end;
if (folderMatches <> 1) then
begin
imap.Logout();
imap.Disconnect();
Memo1.Lines.Add('Expected one selectable folder with the \All special-use attribute. Check label visibility.');
Exit;
end;
success := imap.ExamineMailbox(allMail);
if (success <> 1) then
begin
imap.Logout();
imap.Disconnect();
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 := TChilkatStringBuilder.Create(Self);
quoted.Append(query);
if ((quoted.Contains(#13,1) = 1) or (quoted.Contains(#10,1) = 1)) then
begin
imap.Logout();
imap.Disconnect();
Memo1.Lines.Add('A search query must not contain CR or LF.');
Exit;
end;
replacements := quoted.Replace('\','\\');
replacements := quoted.Replace('"','\"');
joined1 := TChilkatStringBuilder.Create(Self);
joined1.Append('X-GM-RAW "');
joined1.Append(quoted.GetAsString());
joined1.Append('"');
criteria := joined1.GetAsString();
found := TMessageSet.Create(Self);
success := imap.QueryMbx(criteria,1,found.ControlInterface);
if (success <> 1) then
begin
imap.Logout();
imap.Disconnect();
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(found.Count));
Memo1.Lines.Add('UID set: ' + found.ToCompactString());
imap.Logout();
imap.Disconnect();