Gmail API Service Account & Domain-Wide Delegation: The 2026 Guide for Developers
Set up Gmail API service account with domain-wide delegation: full Admin Console steps, required scopes, hard limits, and an honest decision framework for when DWD is the wrong choice. Plus: the managed OAuth alternative that skips the admin dance entirely.
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Load service account credentials
creds = service_account.Credentials
.from_service_account_file(
'service-account-key.json',
scopes=['https://mail.google.com/']
)
# Impersonate a workspace user (DWD)
delegated = creds.with_subject(
'user@yourdomain.com'
)
# Build Gmail service
service = build('gmail', 'v1', credentials=delegated)What is a Gmail API service account?
A Gmail API service account with domain-wide delegation is a Google Cloud identity that allows a backend application to access Gmail data for any user in a Google Workspace organization - without individual user consent. The service account is granted admin-level trust in the Google Workspace Admin Console, enabling it to impersonate any user in the domain using OAuth 2.0 JWT authentication.
Unlike standard OAuth 2.0 where each user authorizes your app interactively, gmail api service account domain-wide delegation lets your server code call Gmail APIs on behalf of hundreds or thousands of workspace users with a single service account credential. The tradeoff: it only works on Google Workspace domains - not on personal @gmail.com accounts.
This pattern is common in enterprise tooling: email archiving systems, compliance monitoring platforms, internal CRM integrations, and calendar/email sync services that need to operate across an entire company domain without asking each employee to individually authorize the app.
No user consent flow
Service account accesses Gmail on behalf of workspace users without triggering OAuth prompts.
Server-to-server auth
Uses JWT signed with a private key - no browser redirect, no authorization code exchange.
Domain-scoped access
Authorized once by a Workspace Super Admin - applies across all users in the organization.
Service Account vs OAuth user-side: which one do you actually need?
Both patterns use OAuth 2.0 scopes to access Gmail, but they are fundamentally different in architecture, setup cost, and who they work for. Here is the honest comparison - including the managed option that skips both setup paths entirely.
| Criteria | Service Account + DWD | OAuth user-side | Unipile managed |
|---|---|---|---|
| Google Workspace required | Required | Not needed | Not needed |
| @gmail.com support | No - workspace only | Yes | Yes |
| User consent needed | Admin grants, no per-user | Each user consents | OAuth per user, handled |
| Admin Console setup | Required - complex path | Not needed | Not needed |
| Scope verification by Google | Required for restricted | Required for restricted | Unipile is CASA Tier 2 |
| CASA assessment | Your burden | Your burden | Already done |
| Multi-tenant SaaS friendliness | Hard - per-tenant admin | Good | Excellent |
| Time to first API call | Days (admin approval + setup) | Hours | Minutes |
Use service account + DWD when...
Use OAuth user-side when...
Critical limit: DWD does not work on @gmail.com accounts
This is the most common mistake teams make when choosing gmail api service account domain-wide delegation. DWD can only impersonate users who belong to a Google Workspace domain that has explicitly authorized your service account's client ID. Personal @gmail.com addresses are not part of any Workspace domain and cannot be impersonated - the API call will return a 400 error with admin_policy_enforced or an invalid delegation error. If your product serves both @gmail.com and Workspace users, service account + DWD is not the right choice.
Need Gmail access without Workspace admin? Unipile's managed OAuth works for @gmail.com and Workspace users with a single unified API - no DWD setup required.
Use Unipile's keyHow to set up domain-wide delegation in Google Workspace (5 steps)
Here is the complete 2026 procedure for configuring gmail api service account domain-wide delegation. You need a Google Cloud project, a Workspace Super Admin, and about 30 minutes for the first setup.
Create a service account in Google Cloud Console
Go to console.cloud.google.com, select your project (or create one), then navigate to IAM & Admin > Service Accounts > Create Service Account. Give it a descriptive name like gmail-dwd-service. You do not need to assign any Cloud IAM roles at this stage - the permissions come from Google Workspace Admin Console, not from Cloud IAM.
Generate and download the JSON key
In the service account detail page, go to Keys > Add Key > Create new key > JSON. Download the file - this is the credential your application will use to sign JWTs. Store it securely: treat the JSON key like a private SSL certificate. Never commit it to version control.
The JSON file contains the client_email, private_key, and client_id fields your code needs. As an alternative to file-based keys, you can use Workload Identity Federation for keyless authentication in production environments.
Enable Gmail API and identify required scopes
In Google Cloud Console, go to APIs & Services > Enable APIs and Services and enable the Gmail API. Then decide which OAuth scopes your application needs. For most Gmail operations you need at minimum https://www.googleapis.com/auth/gmail.readonly (sensitive) or https://mail.google.com/ (restricted).
https://mail.google.com/) require a formal Google security review and CASA Tier 2 assessment before you can use them in production. See the full scope reference in the next section and in the Gmail OAuth scopes deep-dive for details on the review process.Authorize the client ID in Admin Console
This is the step that requires your Google Workspace Super Admin. Navigate in the Admin Console to:
In the "Add new" dialog, enter the service account's numeric client ID (the Unique ID you noted in Step 1) and the list of OAuth scopes separated by commas. For example:
Save the entry. Changes typically propagate within a few minutes but can take up to 60 minutes in large organizations. Reference: Google Workspace Admin Help - Control API access with domain-wide delegation.
Impersonate a user from your backend
With the service account key downloaded and DWD authorized, you can now call Gmail APIs on behalf of any user in the domain. The key step is calling with_subject() on the credentials to set the user to impersonate.
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
SERVICE_ACCOUNT_FILE = 'service-account-key.json'
# Load base credentials from JSON key
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES
)
# Impersonate the target workspace user (DWD)
delegated_creds = credentials.with_subject('user@yourdomain.com')
# Build the Gmail service with delegated credentials
service = build('gmail', 'v1', credentials=delegated_creds)
# List the user's inbox labels
results = service.users().labels().list(userId='me').execute()
print(results)const { google } = require('googleapis');
const auth = new google.auth.GoogleAuth({
keyFile: 'service-account-key.json',
scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
// Set the user to impersonate (DWD)
clientOptions: { subject: 'user@yourdomain.com' }
});
const gmail = google.gmail({ version: 'v1', auth });
// List labels for the impersonated user
const res = await gmail.users.labels.list({ userId: 'me' });
console.log(res.data.labels);Required OAuth scopes for Gmail DWD
Google classifies Gmail API scopes into three tiers: basic, sensitive, and restricted. The tier determines how much scrutiny Google applies before you can use the scope in production. For domain-wide delegation, you must list all scopes in the Admin Console authorization entry. For a full breakdown of every scope and what Google's verification process looks like, see the Gmail OAuth Scopes deep-dive.
| Scope | Access level | Tier | Google review required |
|---|---|---|---|
| https://www.googleapis.com/auth/gmail.readonly | Read all messages and metadata | Sensitive | Yes - OAuth consent screen verification |
| https://www.googleapis.com/auth/gmail.send | Send email on behalf of user | Sensitive | Yes - OAuth consent screen verification |
| https://www.googleapis.com/auth/gmail.modify | Read, compose, send, delete (not permanently) | Sensitive | Yes - OAuth consent screen verification |
| https://www.googleapis.com/auth/gmail.labels | Create, read, update, delete labels | Basic | No |
| https://www.googleapis.com/auth/gmail.metadata | Read message metadata (headers, no body) | Basic | No |
| https://mail.google.com/ | Full access - read, write, send, delete all | Restricted | Yes - full security assessment + CASA Tier 2 |
| https://www.googleapis.com/auth/gmail.settings.basic | Manage basic mail settings (filters, labels) | Sensitive | Yes - OAuth consent screen verification |
| https://www.googleapis.com/auth/gmail.settings.sharing | Manage sensitive settings (forwarding, IMAP/POP) | Restricted | Yes - full security assessment + CASA Tier 2 |
Gmail-specific limits and gotchas
Before committing to gmail api service account domain-wide delegation, know these constraints. Some are hard technical limits from Google; others are policy requirements that can block your app from going live. For troubleshooting errors like admin_policy_enforced, see the Gmail API errors guide.
125 delegates max per user
Gmail enforces a hard limit of 25 mail delegates per user account. This is a per-user quota enforced at the Gmail level, not the Google Cloud API quota level. If you are building a compliance or archiving tool that needs to operate across a large organization, plan your architecture around this limit early. You cannot request an increase from Google.
2Primary email required, no alias
When calling with_subject() or setting the JWT sub claim, you must use the user's primary email address, not an alias or a group email. For example, if a user's primary address is john@company.com but they also have john.smith@company.com as an alias, you must use the primary. Using an alias will result in an authentication error from the Gmail API.
Similarly, group email addresses (like team@company.com) cannot be impersonated with DWD - groups are not individual user accounts.
3CASA Tier 2 annual assessment for restricted scopes
If your application uses any restricted Gmail scopes (such as https://mail.google.com/), Google requires you to pass a CASA (Cloud Application Security Assessment) Tier 2 evaluation before your app can access Gmail data for external users. This is an annual requirement, not a one-time certification.
CASA Tier 2 is conducted by a Google-approved security assessor. The assessment covers your app's security architecture, data handling practices, and access controls. Timeline: budget 4-8 weeks and real cost. This is a significant barrier for early-stage teams.
4Multi-party approvals (Google August 2024 update)
Starting August 2024, Google introduced multi-party approval for certain high-privilege administrative actions in Google Workspace. Depending on your Workspace edition (Business Standard, Enterprise, etc.) and your organization's security settings, authorizing a new client ID for domain-wide delegation may now require a second Super Admin to confirm the action before it takes effect.
This means the path of "get one admin to authorize DWD" is no longer guaranteed to work in one step for all organizations. Check your organization's Workspace admin policies and the Google Workspace Updates blog for the latest requirements before starting the setup process with a customer's IT team.
When NOT to use service account + DWD (the SaaS multi-tenant problem)
This section is the one most guides skip. Gmail API service account domain-wide delegation is a powerful but narrow tool. If any of these scenarios describe your situation, DWD will either not work at all, or create operational overhead that outweighs the benefit. Choosing DWD in these cases is a common and costly mistake.
B2C or PLG product serving @gmail.com users
If your product has a self-serve sign-up flow and your users include people with personal @gmail.com accounts, DWD is architecturally incompatible with your use case. DWD cannot impersonate @gmail.com accounts - full stop. You need standard OAuth user-side authorization for every user who signs up, regardless of whether they also happen to have a Workspace account.
Multi-tenant SaaS with customers on different Workspace domains
If each of your customers is a different company with their own Google Workspace domain, you would need a separate DWD authorization from a Super Admin at every single customer organization. This is not scalable. Each customer's IT admin must follow the 5-step setup process independently. Standard OAuth user-side authorization - or a managed OAuth solution - is far better suited for multi-tenant products where your users span many different organizations.
No access to a Google Workspace Super Admin
DWD requires a Google Workspace Super Admin to authorize your service account's client ID in the Admin Console. If your target users or your own organization does not have a Super Admin available, or if the IT approval process takes weeks to months, DWD will block your entire go-to-market. This is common in regulated industries, large enterprises, and organizations with strict change management processes.
Short time-to-market, no CASA budget yet
If you are pre-product-market-fit and need Gmail integration running in days rather than weeks, the combined timeline of: (1) creating a Google Cloud project, (2) waiting for Admin Console propagation, (3) going through Google's OAuth app verification for sensitive scopes, and (4) planning CASA Tier 2 for restricted scopes - is prohibitive. The admin dance alone can take longer than your sprint. A managed OAuth provider that has already passed these reviews is a legitimate engineering choice, not just a shortcut.
Skip the admin dance
Unipile provides hosted OAuth for Gmail, Outlook, and IMAP. CASA Tier 2 certified. No DWD setup, no Admin Console. Works for @gmail.com and Workspace users alike.
The managed alternative: hosted OAuth with Unipile
If your situation makes gmail api service account domain-wide delegation the wrong choice - or if you simply want to avoid the 5-step setup, CASA assessment, and annual renewal - there is a legitimate engineering alternative. Unipile acts as an independent technical intermediary, managing the OAuth flow on behalf of each authenticated user. This is not a workaround for Google's security review. Unipile has completed CASA Tier 2 certification and operates under Google's approved framework.
CASA Tier 2 certified
Unipile has passed Google's Cloud Application Security Assessment at Tier 2. Your linked accounts access Gmail through an already-verified platform - no assessment on your side.
On behalf of each user
Every API call Unipile makes to Gmail is on behalf of each authenticated user individually, using their own OAuth token. No shared credentials, no domain-wide impersonation required.
Single unified API
One API for Gmail, Outlook, and IMAP. Switch providers or add new linked accounts without changing your integration code.
import requests
# Unipile handles the OAuth flow for each linked account
# No service account, no DWD, no Admin Console setup needed
headers = {
"X-API-KEY": "YOUR_UNIPILE_API_KEY",
"accept": "application/json"
}
# List emails from a linked Gmail or Outlook account
response = requests.get(
"https://api.unipile.com/api/v1/emails",
headers=headers,
params={"account_id": "acc_user_gmail_123"}
)
print(response.json())Gmail API Service Account & DWD FAQ
Common questions about Gmail API service account domain-wide delegation, scopes, limits, and when to choose a managed alternative.
A Gmail service account is a special Google Cloud identity (not a human user) that authenticates to the Gmail API using a private JSON key rather than interactive OAuth. When combined with domain-wide delegation, it allows a server-side application to access Gmail on behalf of any user in a Google Workspace organization, without that user needing to authorize the app manually. It is designed for automated, server-to-server access in enterprise environments.
A Gmail API service account + DWD uses server-to-server JWT authentication and can silently impersonate any Workspace user, with no consent flow per user. Standard OAuth user-side requires each user to go through an interactive consent screen, but works for any Gmail user including personal @gmail.com accounts. Service accounts suit enterprise internal tools; OAuth user-side suits SaaS products with diverse user bases. For a full comparison including the managed option, see the comparison table above.
Learn more on Unipile Gmail API product page.No. This is the most critical limit of Gmail API service account domain-wide delegation. Personal @gmail.com addresses are not part of a managed Workspace domain, so there is no admin to authorize the DWD delegation. Attempting to impersonate a @gmail.com user will return an authentication error. If your product serves users with @gmail.com accounts, you must use standard OAuth user-side authorization, or a managed provider like Unipile that handles OAuth for both @gmail.com and Workspace users.
In the Google Workspace Admin Console (requires Super Admin), navigate to: Menu > Security > Access and data control > API controls > Domain-wide delegation > Manage Domain-Wide Delegation > Add new. Enter your service account's numeric client ID and the comma-separated list of OAuth scopes. Save and wait up to 60 minutes for propagation. For the complete step-by-step, see the setup guide in this article. Reference: Google Admin Help - Domain-wide delegation.
Domain-wide delegation is not deprecated as of 2026, but it is more restricted. Google introduced multi-party approval for certain high-privilege admin actions in August 2024, which may require a second Super Admin to approve DWD authorizations. Additionally, using restricted Gmail scopes like https://mail.google.com/ now requires a CASA Tier 2 annual security assessment. DWD remains a valid pattern for genuine enterprise internal tool use cases, but the compliance overhead has increased.
Required scopes depend on what your app does. Read-only: https://www.googleapis.com/auth/gmail.readonly (sensitive, needs Google verification). Send email: https://www.googleapis.com/auth/gmail.send (sensitive). Full mailbox access: https://mail.google.com/ (restricted, requires CASA Tier 2 assessment). Metadata only: https://www.googleapis.com/auth/gmail.metadata (basic, no review). You must include all required scopes in the Admin Console DWD entry. See the full scope table in this guide.
Still have questions about Gmail API service account domain-wide delegation? Our team can help you choose the right architecture for your use case.
Talk to an Expert