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 PHP Downloads
<?php
use Chilkat2\AuthGoogle;
use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;
use Chilkat2\Socket;
$success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$key = new JsonObject();
try {
$key->LoadFile('gmail-service-account.json');
} catch (\Chilkat2\Exception $e) {
echo "Could not load the service-account key from the private directory.\n";
exit;
}
$auth = new AuthGoogle();
$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 = new Socket();
$connection->RequireSslCertVerify = true;
try {
$connection->Connect('www.googleapis.com', 443, true, 10000);
} catch (\Chilkat2\Exception $e) {
echo "Could not establish the Google token connection.\n";
exit;
}
try {
$auth->ObtainAccessToken($connection);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
$connection->Close(1000);
if (!$success) {
echo "Token exchange failed. Check the key, delegated scopes, user, and computer clock.\n";
exit;
}
$http = new Http();
$http->RequireSslCertVerify = true;
$http->AuthToken = $auth->AccessToken;
$resp = new HttpResponse();
$reply = new JsonObject();
try {
$http->HttpNoBody('GET', 'https://gmail.googleapis.com/gmail/v1/users/me/profile', $resp);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($resp->StatusCode == 0) {
echo "Gmail did not return an HTTP response.\n";
exit;
}
if ((!$success) || (($resp->StatusCode < 200) || ($resp->StatusCode >= 300))) {
echo 'Gmail HTTP ', $resp->StatusCode, "\n";
try {
$reply->Load($resp->BodyStr);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($success) {
echo $reply->StringOf('error.message'), "\n";
}
exit;
}
try {
$reply->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
echo "Expected a Gmail JSON response.\n";
exit;
}
if (($reply->JsonTypeOf('emailAddress') != 1) || ($reply->StringOfEquals('emailAddress', '', true))) {
echo "Expected emailAddress in the response.\n";
exit;
}
echo 'Authorized mailbox: ', $reply->StringOf('emailAddress'), "\n";
echo 'Messages: ', $reply->IntOf('messagesTotal'), "\n";