Access a Google Workspace mailbox with a service account
See more GMail REST API Examples
A Google Workspace super administrator must authorize the service account client ID for https://www.googleapis.com/auth/gmail.metadata in Admin console domain-wide delegation. Enable the Gmail API in the Cloud project. Set SubEmailAddress to a Gmail-enabled user in that organization. The profile response identifies the mailbox represented by me.
Store the downloaded JSON service-account key in gmail-service-account.json in a private working directory. AuthGoogle signs a JWT with the key and exchanges it for an access token. Repeat that exchange when the token expires. For other operations, change Scope and grant that scope in the Admin console. This workflow is for organization-controlled applications. Personal Gmail accounts can use offline authorization with a refresh token.
Chilkat Lazarus Pascal Downloads
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.Http,
Chilkat.AuthGoogle,
Chilkat.HttpResponse,
Chilkat.JsonObject,
Chilkat.Socket;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
key: TJsonObject;
auth: TAuthGoogle;
connection: TSocket;
http: THttp;
resp: THttpResponse;
reply: TJsonObject;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
key := TJsonObject.Create;
success := key.LoadFile('gmail-service-account.json');
if (success <> True) then
begin
WriteLn('Could not load the service-account key from the private directory.');
Exit;
end;
auth := TAuthGoogle.Create;
auth.JsonKey := key.Emit();
auth.Scope := 'https://www.googleapis.com/auth/gmail.metadata';
auth.SubEmailAddress := 'user@example.com';
auth.ExpireNumSeconds := 3600;
// Obtain a token for the named Workspace user. Keep the computer clock accurate.
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('Token exchange failed. Check the key, delegated scopes, user, and computer clock.');
Exit;
end;
http := THttp.Create;
http.RequireSslCertVerify := True;
http.AuthToken := auth.AccessToken;
resp := THttpResponse.Create;
reply := TJsonObject.Create;
success := http.HttpNoBody('GET','https://gmail.googleapis.com/gmail/v1/users/me/profile',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;
if ((reply.JsonTypeOf('emailAddress') <> 1) or (reply.StringOfEquals('emailAddress','',True) = True)) then
begin
WriteLn('Expected emailAddress in the response.');
Exit;
end;
WriteLn('Authorized mailbox: ' + reply.StringOf('emailAddress'));
WriteLn('Messages: ' + reply.IntOf('messagesTotal'));
key.Free;
auth.Free;
connection.Free;
http.Free;
resp.Free;
reply.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.