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: