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

Check Gmail from a scheduled job after one-time consent

See more GMail REST API Examples

First run desktop authorization with gmail.readonly and offline access. This applies to personal Gmail and Workspace accounts subject to organization policies. Configure a job to run this code using the same private working directory and user identity. Each run refreshes the token and displays up to ten inbox message headers.

Save the original OAuth client credentials in a private gmail-client.json containing client_id and client_secret. The existing gmail-token.json supplies the refresh token. Use protected credential storage in a deployed application and serialize runs sharing these files. An invalid_grant response requires reconnecting the account. External OAuth apps in Testing normally receive refresh tokens that expire after seven days when Gmail scopes are requested. Google token expiration guidance.

This is a repeatable inbox check. To process each mailbox change across runs, see mailbox synchronization.

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.FileAccess,
  Chilkat.HttpResponse,
  Chilkat.HttpRequest,
  Chilkat.JsonObject,
  Chilkat.StringBuilder,
  Chilkat.Http;

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

procedure RunDemo;
var
  success: Boolean;
  files: TFileAccess;
  fileStatus: Integer;
  backupStatus: Integer;
  token: TJsonObject;
  client: TJsonObject;
  http: THttp;
  form: THttpRequest;
  resp: THttpResponse;
  reply: TJsonObject;
  ids: TStringTable;
  i: Integer;
  url: TStringBuilder;
  h: Integer;

begin
  success := False;

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

  files := TFileAccess.Create;
  //  Recover the previous complete file if a run stopped during replacement.
  fileStatus := files.FileExists3('gmail-token.json');
  if (fileStatus < 0) then
    begin
      WriteLn('Could not inspect gmail-token.json.');
      Exit;
    end;
  if (fileStatus = 0) then
    begin
      backupStatus := files.FileExists3('gmail-token.json.previous');
      if (backupStatus < 0) then
        begin
          WriteLn('Could not inspect the backup file.');
          Exit;
        end;
      if (backupStatus = 1) then
        begin
          success := files.FileRename('gmail-token.json.previous','gmail-token.json');
          if (success <> True) then
            begin
              WriteLn('Could not restore the previous complete file.');
              Exit;
            end;
          fileStatus := 1;
        end;
    end;
  token := TJsonObject.Create;
  success := token.LoadFile('gmail-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not read gmail-token.json from the private working directory.');
      Exit;
    end;
  if ((token.JsonTypeOf('refresh_token') <> 1) or (token.StringOfEquals('refresh_token','',True) = True)) then
    begin
      WriteLn('Authorize this account for offline access first.');
      Exit;
    end;
  client := TJsonObject.Create;
  success := client.LoadFile('gmail-client.json');
  if (success <> True) then
    begin
      WriteLn('Could not load the private OAuth client file.');
      Exit;
    end;
  if ((client.JsonTypeOf('client_id') <> 1) or (client.JsonTypeOf('client_secret') <> 1)) then
    begin
      WriteLn('gmail-client.json must contain client_id and client_secret.');
      Exit;
    end;
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  form := THttpRequest.Create;
  form.HttpVerb := 'POST';
  form.ContentType := 'application/x-www-form-urlencoded';
  form.AddParam('grant_type','refresh_token');
  form.AddParam('client_id',client.StringOf('client_id'));
  form.AddParam('client_secret',client.StringOf('client_secret'));
  form.AddParam('refresh_token',token.StringOf('refresh_token'));
  resp := THttpResponse.Create;
  reply := TJsonObject.Create;
  success := http.HttpReq('https://oauth2.googleapis.com/token',form,resp);
  if (resp.StatusCode = 0) then
    begin
      WriteLn('The token endpoint did not return an HTTP response.');
      Exit;
    end;
  if ((success <> True) or (resp.StatusCode <> 200)) then
    begin
      WriteLn('Token refresh failed. HTTP ' + resp.StatusCode);
      success := reply.Load(resp.BodyStr);
      if (success = True) then
        begin
          if (reply.StringOfEquals('error','invalid_grant',True) = True) then
            begin
              WriteLn('Reconnect this account with interactive authorization.');
            end;
        end;
      Exit;
    end;
  success := reply.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Could not parse the refresh response.');
      Exit;
    end;
  if ((reply.JsonTypeOf('access_token') <> 1) or (reply.StringOfEquals('access_token','',True) = True)) then
    begin
      WriteLn('Expected access_token in the response.');
      Exit;
    end;
  //  Google usually omits the refresh token. Preserve it unless a replacement is returned.
  if ((reply.JsonTypeOf('refresh_token') <> 1) or (reply.StringOfEquals('refresh_token','',True) = True)) then
    begin
      success := reply.UpdateString('refresh_token',token.StringOf('refresh_token'));
      if (success <> True) then
        begin
          WriteLn(reply.LastErrorText);
          Exit;
        end;
    end;
  if ((reply.HasMember('scope') <> True) and (token.JsonTypeOf('scope') = 1)) then
    begin
      success := reply.UpdateString('scope',token.StringOf('scope'));
      if (success <> True) then
        begin
          WriteLn(reply.LastErrorText);
          Exit;
        end;
    end;
  //  Prepare the complete replacement before moving the last committed file.
  success := reply.WriteFile('gmail-token.json.new');
  if (success <> True) then
    begin
      WriteLn('Could not write the replacement file.');
      Exit;
    end;
  if (files.FileExists('gmail-token.json') = True) then
    begin
      if (files.FileExists('gmail-token.json.previous') = True) then
        begin
          success := files.FileDelete('gmail-token.json.previous');
          if (success <> True) then
            begin
              WriteLn('Could not rotate the previous backup.');
              Exit;
            end;
        end;
      success := files.FileRename('gmail-token.json','gmail-token.json.previous');
      if (success <> True) then
        begin
          WriteLn('Could not retain the previous complete file.');
          Exit;
        end;
    end;
  success := files.FileRename('gmail-token.json.new','gmail-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not commit the replacement. The previous complete file is retained.');
      Exit;
    end;

  http.AuthToken := reply.StringOf('access_token');
  success := http.HttpNoBody('GET','https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&maxResults=10',resp);
  if (resp.StatusCode = 0) then
    begin
      WriteLn('Gmail did not return an HTTP response.');
      Exit;
    end;
  if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
    begin
      WriteLn('Gmail HTTP ' + resp.StatusCode);
      success := reply.Load(resp.BodyStr);
      if (success = True) then
        begin
          WriteLn(reply.StringOf('error.message'));
        end;
      Exit;
    end;
  success := reply.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Expected a Gmail JSON response.');
      Exit;
    end;
  ids := TStringTable.Create;
  i := 0;
  while (i < reply.SizeOfArray('messages')) do
    begin
      reply.I := i;
      success := ids.Append(reply.StringOf('messages[i].id'));
      if (success <> True) then
        begin
          WriteLn(ids.LastErrorText);
          Exit;
        end;
      i := i + 1;
    end;

  url := TStringBuilder.Create;
  i := 0;
  while (i < ids.Count) do
    begin
      url.SetString('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
      url.Append(http.UrlEncode(ids.StringAt(i)));
      url.Append('?format=metadata&metadataHeaders=From&metadataHeaders=Subject');
      success := http.HttpNoBody('GET',url.GetAsString(),resp);
      if (resp.StatusCode = 0) then
        begin
          WriteLn('Gmail did not return an HTTP response.');
          Exit;
        end;
      if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
        begin
          WriteLn('Gmail HTTP ' + resp.StatusCode);
          success := reply.Load(resp.BodyStr);
          if (success = True) then
            begin
              WriteLn(reply.StringOf('error.message'));
            end;
          Exit;
        end;
      success := reply.Load(resp.BodyStr);
      if (success <> True) then
        begin
          WriteLn('Expected a Gmail JSON response.');
          Exit;
        end;
      WriteLn('Message: ' + ids.StringAt(i));
      h := 0;
      while (h < reply.SizeOfArray('payload.headers')) do
        begin
          reply.I := h;
          WriteLn(reply.StringOf('payload.headers[i].name') + ': ' + reply.StringOf('payload.headers[i].value'));
          h := h + 1;
        end;

      i := i + 1;
    end;

  WriteLn('Inbox messages checked: ' + ids.Count);


  files.Free;
  token.Free;
  client.Free;
  http.Free;
  form.Free;
  resp.Free;
  reply.Free;
  ids.Free;
  url.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.