Setup Google Workspace Account for Sending SMTP GMail from a Service Account
To send email via SMTP from a Google service account in a Google Workspace domain, you must use OAuth2 with domain-wide delegation to impersonate a user. This allows your service account to act as a real user, meaning a non-GMail email address (e.g., joe@example.com) and send mail via smtp.gmail.com.
Here's a complete step-by-step guide:
Prerequisites
- A Google Workspace (formerly G Suite) domain.
- Access to the Google Cloud Console.
- Admin access to the Google Workspace Admin Console.
- Your app must use the XOAUTH2 mechanism to authenticate with smtp.gmail.com.
Step-by-Step Setup
1. Create a Service Account
- Go to IAM & Admin > Service Accounts.
- Click Create Service Account.
- Name it, and grant no roles for now.
- Click Done.
2. Enable Domain-Wide Delegation
- Edit your service account.
- Go to Advanced Settings.

- Note the Client ID that appears (you’ll use this later). In the above image the Client ID is
109122032928932715958 - Go to: Google Workspace Admin Console
- In the Admin Console, go to Security / Access and data control / API controls. Then click on Manage Domain Wide Delegation.

- Click Add new and add an entry for your google service account using the service account email address,
Client ID, and the scopehttps://mail.google.com/. It should look like this when finished:
3. Permission to Create a Service Account Key
- You'll first need to make sure your account has permission to create a key. If not, you'll get this error:

- Open the project picker:

- Click on the 3 dots at the top right ("More Actions") and select IAM/Permissions:

- Click on Grant Access:

- The principal is your email address (non-GMail address, such as
info@chilkat.xyz), the role to assign is Organization Policy Administrator
- Next, go to Organization Policies:

- Type
"key creation"in the Filter, and selectDisable service account key creation:
- Edit the
iam.disableServiceAccountKeyCreation-Managed (Legacy)policy.
- Choose
Override parent's policy, andNot enforced
4. Create a Service Account Key
Now that you have permission to create a service account key, go ahead and create a P12 key. A .p12 is a PKCS#12 file which is also called a PFX file (.pfx).
5. GMail SMTP Examples using a Google Service Account
The links below show how to obtain an access token with a Google service account's .p12 key and use it to send emails through the Gmail SMTP server.
The links below show how to obtain an access token with a Google service account's JSON key and use it to send emails through the Gmail SMTP server.