Skip to main content
The pinned setup omits required API enablement and Workspace scope authorization. Its run path is stale, and its environment guard checks only the service-account file even though Gmail requires GOOGLE_DELEGATED_USER. Complete the generated setup and use the generated run command below.
service_account.py

Run the Example

1

Set up your virtual environment

2

Install dependencies

3

Export environment variables

4

Create the delegated service account

Enable the Gmail, Google Calendar, Google Drive, and Google Sheets APIs in the Google Cloud project. Create a service account, enable domain-wide delegation, and download its JSON key. See Delegating domain-wide authority.
5

Authorize the Workspace scopes

As a Workspace super admin, add the service account’s numeric client ID under Security > Access and data control > API Controls > Manage Domain Wide Delegation. Authorize https://www.googleapis.com/auth/gmail.readonly, https://www.googleapis.com/auth/gmail.modify, https://www.googleapis.com/auth/gmail.compose, https://www.googleapis.com/auth/calendar.readonly, https://www.googleapis.com/auth/calendar, https://www.googleapis.com/auth/drive.readonly, and https://www.googleapis.com/auth/spreadsheets.readonly.
6

Require the delegated user

Replace if not getenv("GOOGLE_SERVICE_ACCOUNT_FILE"): with if not getenv("GOOGLE_SERVICE_ACCOUNT_FILE") or not getenv("GOOGLE_DELEGATED_USER"): in the saved file.
7

Run the example

Save the code above as service_account.py, then run:
Full source: cookbook/91_tools/google/workspace/service_account.py