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

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Mailboxes,
  Chilkat.StringBuilder,
  Chilkat.Imap,
  Chilkat.JsonObject,
  Chilkat.MessageSet;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  replacements: Integer;
  token: TJsonObject;
  mailbox: string;
  imap: TImap;
  capabilities: string;
  folders: TMailboxes;
  allMail: string;
  folderMatches: Integer;
  f: Integer;
  query: string;
  quoted: TStringBuilder;
  joined1: TStringBuilder;
  criteria: string;
  found: TMessageSet;

begin
  success := False;

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

  token := TJsonObject.Create;
  success := token.LoadFile('gmail-mail-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not load the protocol token from the private working directory.');
      Exit;
    end;
  if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
    begin
      WriteLn('Authorize or refresh the mailbox first.');
      Exit;
    end;
  mailbox := 'user@example.com';
  imap := TImap.Create;
  imap.Ssl := True;
  imap.Port := 993;
  imap.RequireSslCertVerify := True;
  imap.AuthMethod := 'XOAUTH2';
  success := imap.Connect('imap.gmail.com');
  if (success <> True) then
    begin
      WriteLn('Could not establish the Gmail IMAP TLS connection.');
      Exit;
    end;
  success := imap.Login(mailbox,token.StringOf('access_token'));
  if (success <> True) then
    begin
      imap.Disconnect();
      WriteLn('IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.');
      Exit;
    end;
  capabilities := imap.Capability();
  if ((imap.LastMethodSuccess <> True) or (imap.HasCapability('X-GM-EXT-1',capabilities) <> True)) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Gmail IMAP extensions are unavailable.');
      Exit;
    end;
  folders := TMailboxes.Create;
  success := imap.MbxList(False,'','*',folders);
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Could not list Gmail folders.');
      Exit;
    end;
  allMail := '';
  folderMatches := 0;
  f := 0;
  while (f < folders.Count) do
    begin
      if ((folders.HasFlag(f,'\All') = True) and (folders.IsSelectable(f) = True)) then
        begin
          allMail := folders.GetName(f);
          folderMatches := folderMatches + 1;
        end;
      f := f + 1;
    end;

  if (folderMatches <> 1) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Expected one selectable folder with the \All special-use attribute. Check label visibility.');
      Exit;
    end;
  success := imap.ExamineMailbox(allMail);
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('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 := TStringBuilder.Create;
  quoted.Append(query);
  if ((quoted.Contains(#13,True) = True) or (quoted.Contains(#10,True) = True)) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('A search query must not contain CR or LF.');
      Exit;
    end;
  replacements := quoted.Replace('\','\\');
  replacements := quoted.Replace('"','\"');
  joined1 := TStringBuilder.Create;
  joined1.Append('X-GM-RAW "');
  joined1.Append(quoted.GetAsString());
  joined1.Append('"');
  criteria := joined1.GetAsString();
  found := TMessageSet.Create;
  success := imap.QueryMbx(criteria,True,found);
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Gmail search failed.');
      Exit;
    end;
  //  Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
  WriteLn('Matching messages: ' + found.Count);
  WriteLn('UID set: ' + found.ToCompactString());
  imap.Logout();
  imap.Disconnect();


  token.Free;
  imap.Free;
  folders.Free;
  quoted.Free;
  joined1.Free;
  found.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.