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

Authorize a desktop application to use Gmail

See more GMail REST API Examples

Enable the Gmail API, configure the OAuth consent screen, and create a Desktop app OAuth client. Launch the system browser and receive the authorization code on a loopback listener. The sample requests read-only access with PKCE and offline access. For another operation, select the scope in that example before authorizing. Gmail scopes.

Run in a private, user-only directory. The file contains bearer credentials. In a deployed application use protected credential storage. To reuse an existing grant, copy the older examples’ qa_data/tokens/gmail.json to gmail-token.json in this private directory. The token retains its original scopes. Gmail clients using IMAP, POP, or SMTP with OAuth need the https://mail.google.com/ scope. Use a separate cache for each user and client.

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.OAuth2,
  Chilkat.JsonObject;

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

procedure RunDemo;
var
  success: Boolean;
  oauth: TOAuth2;
  authUrl: string;
  waited: Integer;
  token: TJsonObject;

begin
  success := False;

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

  oauth := TOAuth2.Create;
  oauth.TokenEndpoint := 'https://oauth2.googleapis.com/token';
  oauth.ClientId := 'YOUR_DESKTOP_CLIENT_ID';
  oauth.ClientSecret := 'YOUR_DESKTOP_CLIENT_SECRET';

  oauth.AuthorizationEndpoint := 'https://accounts.google.com/o/oauth2/v2/auth';
  oauth.LocalHost := '127.0.0.1';
  oauth.ListenPort := 55568;
  oauth.ListenPortRangeEnd := 55578;
  oauth.CodeChallenge := True;
  oauth.CodeChallengeMethod := 'S256';
  oauth.Scope := 'https://www.googleapis.com/auth/gmail.readonly';
  success := oauth.AddAuthQueryParam('access_type','offline');
  if (success <> True) then
    begin
      WriteLn('Could not configure offline access.');
      Exit;
    end;
  //  This is the interactive setup step. Subsequent refreshes use the saved refresh token.
  success := oauth.AddAuthQueryParam('prompt','consent');
  if (success <> True) then
    begin
      WriteLn('Could not configure consent.');
      Exit;
    end;
  authUrl := oauth.StartAuth();
  if (oauth.LastMethodSuccess <> True) then
    begin
      WriteLn('Could not start the loopback listener.');
      Exit;
    end;
  success := oauth.LaunchBrowser(authUrl);
  if (success <> True) then
    begin
      oauth.Cancel();
      WriteLn('Could not open the system browser.');
      Exit;
    end;
  waited := 0;
  while ((oauth.AuthFlowState < 3) and (waited < 180000)) do
    begin
      oauth.SleepMs(200);
      waited := waited + 200;
    end;

  if (oauth.AuthFlowState < 3) then
    begin
      oauth.Cancel();
      WriteLn('Authorization timed out.');
      Exit;
    end;
  if (oauth.AuthFlowState <> 3) then
    begin
      WriteLn('Authorization did not complete. Flow state: ' + oauth.AuthFlowState);
      Exit;
    end;
  token := TJsonObject.Create;
  success := token.Load(oauth.AccessTokenResponse);
  if (success <> True) then
    begin
      WriteLn('Could not parse the token response.');
      Exit;
    end;
  if ((token.JsonTypeOf('refresh_token') <> 1) or (token.StringOfEquals('refresh_token','',True) = True)) then
    begin
      WriteLn('No offline refresh token was issued. The existing cache was preserved.');
      Exit;
    end;
  success := token.WriteFile('gmail-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not save the token file.');
      Exit;
    end;
  WriteLn('Credentials saved in the private working directory.');


  oauth.Free;
  token.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.