The Gmail API allows Google Workspace Admins to streamline the workflow of managing delegations for users in their organization. This feature allows Admins to automate the process efficiently and maintain control over delegate access.
To add a Gmail delegation using Python, you can utilize the Gmail API along with the Google API Client Library for Python.
Prerequisites
- Creating a service account
- Delegating domain-wide authority to the service account
- Downloading your service account credentials JSON file
Python Script
The following example code snippet demonstrates how a delegation in Gmail can be set using Python:
from googleapiclient.discovery import build
from google.oauth2 import service_account
SCOPES = ['https://www.googleapis.com/auth/gmail.settings.sharing']
# Location and name of the JSON file / Key of the services account.
SERVICE_ACCOUNT_FILE = 'credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# The account which will be delegated (access without PW).
delegated_credentials = credentials.with_subject('user1@domain.com')
# Create a Gmail service client
service = build('gmail', 'v1', credentials=delegated_credentials)
# The email address where the delegation will be added.
settings = {
'delegateEmail': 'user2@domain.com',
'verificationStatus': 'accepted'
}
request = service.users().settings().delegates().create(userId='me', body=settings).execute()
print('Delegation set successfully!')
Be First to Comment