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

Gmail IMAP: Workspace Service Account with a JSON Key

Use a service-account JSON key with Google Workspace domain-wide delegation. A Workspace administrator must authorize the service account's numeric OAuth client ID for https://mail.google.com/. Set SubEmailAddress to the Workspace user whose active Gmail mailbox is being accessed, and use that same address for IMAP login.

A service account has no Gmail mailbox of its own; leaving the impersonated user empty does not grant access to a personal Gmail account. The signed JWT exchange yields a short-lived token without a refresh token. Obtain another when needed, protect the private key, and keep the computer clock accurate.

This example lists visible folders and examines INBOX read-only. For the different visibility rules of the IMAP-only administrative scope, see gmail.imap_admin delegation.

See the Gmail SMTP, IMAP, and POP3 guide for current authentication choices and Gmail-specific examples.

Reference 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.AuthGoogle,
  Chilkat.Imap,
  Chilkat.JsonObject,
  Chilkat.Socket;

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

procedure RunDemo;
var
  success: Boolean;
  mailbox: string;
  key: TJsonObject;
  auth: TAuthGoogle;
  connection: TSocket;
  imap: TImap;
  folders: TMailboxes;
  i: Integer;

begin
  success := False;

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

  mailbox := 'user@example.com';
  key := TJsonObject.Create;
  success := key.LoadFile('gmail-service-account.json');
  if (success <> True) then
    begin
      WriteLn('Could not load the private service-account key.');
      Exit;
    end;
  if ((key.StringOfEquals('type','service_account',True) <> True) or (key.JsonTypeOf('private_key') <> 1)) then
    begin
      WriteLn('Expected a Google service-account JSON key.');
      Exit;
    end;
  auth := TAuthGoogle.Create;
  auth.JsonKey := key.Emit();
  auth.SubEmailAddress := mailbox;
  auth.Scope := 'https://mail.google.com/';
  auth.ExpireNumSeconds := 3600;
  connection := TSocket.Create;
  connection.RequireSslCertVerify := True;
  success := connection.Connect('www.googleapis.com',443,True,10000);
  if (success <> True) then
    begin
      WriteLn('Could not establish the Google token connection.');
      Exit;
    end;
  success := auth.ObtainAccessToken(connection);
  connection.Close(1000);
  if (success <> True) then
    begin
      WriteLn('Check the key, domain-wide delegation client ID/scope, user, and computer clock.');
      Exit;
    end;
  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,auth.AccessToken);
  if (success <> True) then
    begin
      imap.Disconnect();
      WriteLn('IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.');
      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;
  //  List the labels visible through ordinary full-mail IMAP access.
  i := 0;
  while (i < folders.Count) do
    begin
      WriteLn(folders.GetName(i));
      i := i + 1;
    end;

  success := imap.ExamineMailbox('INBOX');
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Could not examine the impersonated user''s INBOX.');
      Exit;
    end;
  WriteLn('INBOX messages: ' + imap.NumMessages);
  imap.Logout();
  imap.Disconnect();


  key.Free;
  auth.Free;
  connection.Free;
  imap.Free;
  folders.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.