Sample code for 30+ languages & platforms
Lazarus Pascal Requires Chilkat v11.1.0+

Gmail IMAP: Identify Messages and Threads Across Folders

See more GMail SMTP/IMAP/POP Examples

Sample INBOX and the discovered All Mail folder, fetch Gmail message and thread IDs, and deduplicate messages appearing in both. Each X-GM-MSGID maps to an X-GM-THRID; equal thread IDs group messages in a Gmail conversation.

All identifiers are strings. IMAP UIDs identify messages only within one mailbox and UIDVALIDITY. Gmail IDs identify messages across labels, while the RFC Message-ID header is a separate identifier. Gmail IMAP IDs are unsigned decimal values; Gmail REST uses the corresponding hexadecimal strings. Do not pass these decimal strings directly as REST IDs.

The example reads at most ten messages per folder. Its regular expression extracts only the requested numeric metadata from a single-line FETCH result, tolerating attribute order and unrelated notifications. It is not a general IMAP/MIME parser. A vanished message is skipped. No message body is downloaded or marked read.

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.StringTable,
  Chilkat.Imap,
  Chilkat.MessageSet,
  Chilkat.StringBuilder,
  Chilkat.JsonObject,
  Chilkat.Mailboxes;

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

procedure RunDemo;
var
  success: Boolean;
  statusText: TStringBuilder;
  statusMatch: TJsonObject;
  completed: Integer;
  token: TJsonObject;
  mailbox: string;
  imap: TImap;
  capabilities: string;
  folders: TMailboxes;
  allMail: string;
  folderMatches: Integer;
  f: Integer;
  mailboxNames: TStringTable;
  unique: TJsonObject;
  found: TMessageSet;
  uidStrings: TStringTable;
  raw: TStringBuilder;
  captures: TJsonObject;
  folderIndex: Integer;
  selected: string;
  i: Integer;
  uid: string;
  joined1: TStringBuilder;
  response: string;
  joined2: TStringBuilder;
  pattern: string;
  count: Integer;
  messageId: string;
  threadId: string;

begin
  success := False;

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

  statusText := TStringBuilder.Create;
  statusMatch := TJsonObject.Create;

  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;
  mailboxNames := TStringTable.Create;
  mailboxNames.Append('INBOX');
  mailboxNames.Append(allMail);
  unique := TJsonObject.Create;
  found := TMessageSet.Create;
  uidStrings := TStringTable.Create;
  raw := TStringBuilder.Create;
  captures := TJsonObject.Create;
  folderIndex := 0;
  while (folderIndex < mailboxNames.Count) do
    begin
      selected := mailboxNames.StringAt(folderIndex);
      success := imap.ExamineMailbox(selected);
      if (success <> True) then
        begin
          imap.Logout();
          imap.Disconnect();
          WriteLn('Could not open the mailbox read-only.');
          Exit;
        end;
      success := imap.QueryMbx('ALL',True,found);
      if (success <> True) then
        begin
          imap.Logout();
          imap.Disconnect();
          WriteLn('Could not obtain message UIDs.');
          Exit;
        end;
      uidStrings.Clear();
      if (found.Count > 0) then
        begin
          uidStrings.SplitAndAppend(found.ToCommaSeparatedStr(),',',False,False);
        end;
      //  Sample up to 10 messages from each mailbox; this is not a complete synchronization.
      i := 0;
      while ((i < uidStrings.Count) and (i < 10)) do
        begin
          uid := uidStrings.StringAt(i);
          joined1 := TStringBuilder.Create;
          joined1.Append('UID FETCH ');
          joined1.Append(uid);
          joined1.Append(' (UID X-GM-MSGID X-GM-THRID)');
          response := imap.SendRawCommand(joined1.GetAsString());
          statusText.SetString(response);
          //  A completed raw exchange can still return NO or BAD. Require tagged OK.
          completed := statusText.RegexMatch('(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z',statusMatch,1000);

          if ((imap.LastMethodSuccess <> True) or (completed <> 1)) then
            begin
              imap.Logout();
              imap.Disconnect();
              WriteLn('Could not fetch Gmail IDs.');
              Exit;
            end;
          raw.SetString(response);
          //  Match only this UID's metadata line. Attribute order need not be fixed.
          //  Unsolicited EXISTS/EXPUNGE/FLAGS lines do not match these three attributes.
          joined2 := TStringBuilder.Create;
          joined2.Append('(?mi)^\* [0-9]+ FETCH \((?=[^\r\n]*\bUID ');
          joined2.Append(uid);
          joined2.Append('(?: |\)))(?=[^\r\n]*\bX-GM-MSGID ([0-9]+)(?: |\)))(?=[^\r\n]*\bX-GM-THRID ([0-9]+)(?: |\)))[^\r\n]*\)\r?$');
          pattern := joined2.GetAsString();
          count := raw.RegexMatch(pattern,captures,1000);
          if (count < 0) then
            begin
              imap.Logout();
              imap.Disconnect();
              WriteLn('Could not parse the Gmail metadata response.');
              Exit;
            end;
          if (count = 1) then
            begin
              messageId := captures.StringOf('match[0].group[1].cap');
              threadId := captures.StringOf('match[0].group[2].cap');
              if (unique.IndexOf(messageId) < 0) then
                begin
                  //  Direct JSON member names; both IDs remain strings without numeric conversion.
                  unique.AppendString(messageId,threadId);
                  WriteLn('Message ID: ' + messageId + '  Thread ID: ' + threadId);
                end
              else
                begin
                  WriteLn('Already encountered under another label: ' + messageId);
                end;
            end
          else
            begin
              WriteLn('No single metadata row for UID ' + uid + '; it may have disappeared. Skipping.');
            end;
          i := i + 1;
        end;

      folderIndex := folderIndex + 1;
    end;

  imap.Logout();
  imap.Disconnect();
  WriteLn('Unique sampled messages: ' + unique.Size);


  statusText.Free;
  statusMatch.Free;
  token.Free;
  imap.Free;
  folders.Free;
  mailboxNames.Free;
  unique.Free;
  found.Free;
  uidStrings.Free;
  raw.Free;
  captures.Free;
          joined1.Free;
          joined2.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.