Gmail API - 在 Python 中自动转发

Gmail API - Autoforwarding in Python

我一直在努力让它工作一段时间,但我无法通过我收到的这个错误代码。

我使用此代码的目标是在 gmail 中设置转发电子邮件地址。这是 Google 文档:https://developers.google.com/gmail/api/guides/forwarding_settings

我复制并粘贴了代码,但收到相同的错误消息:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/settings/forwardingAddresses?alt=json returned "Bad Request">

错误的请求是迄今为止 return 中最令人沮丧的错误代码。我正在使用具有域范围委托的服务帐户,因此我认为这不是权限问题。我已经复制了代码,所以很难相信 json 包是不正确的。我在整个互联网上都看过,但找不到实际使用此功能的任何人的示例代码。恐怕 GAM 将是我唯一的选择。

def test():

    key_path = 'tokens/admin_client.json'
    API_scopes =['https://www.googleapis.com/auth/gmail.settings.sharing','https://www.googleapis.com/auth/gmail.settings.basic']
    credentials = service_account.Credentials.from_service_account_file(key_path,scopes=API_scopes)

    gmail_service = build('gmail', 'v1', credentials=credentials)
    address = { 'forwardingEmail': 'user2@example.com' }
    gmail_service.users().settings().forwardingAddresses().create(userId='me', body=address).execute()

您正在使用无法访问 Gmail 的服务帐户。

您可以使用服务帐户 impersonate GSuite users or use OAuth to login as a user directly

请尝试我制作的这段代码。它对我有用:

from googleapiclient import discovery, errors
from oauth2client import file, client, tools
from google.oauth2 import service_account

SERVICE_ACCOUNT_FILE = 'service_account.json'
SCOPES = ['https://www.googleapis.com/auth/gmail.settings.sharing']

# The user we want to "impersonate"
USER_EMAIL = "user@domain"
ADDRESS = { 'forwardingEmail': 'user2@domain' }

# Set the crendentials 
credentials = service_account.Credentials.\
    from_service_account_file(SERVICE_ACCOUNT_FILE, scopes= SCOPES)
# Delegate the credentials to the user you want to impersonate
delegated_credentials = credentials.with_subject(USER_EMAIL)

try:
    # Build the Gmail Service
    service = discovery.build('gmail', 'v1', credentials=delegated_credentials)
    # Create the forwardingAddresses:Create endpoint
    result = service.users().settings().forwardingAddresses().\
        create(userId='me', body=ADDRESS).execute()
    if result.get('verificationStatus') == 'accepted':
        body = {
            'emailAddress': result.get('forwardingEmail'),
            'enabled': True,
            'disposition': 'trash'
        }
        # If accepted, update the auto forwarding
        result_update = service.users().settings().\
            updateAutoForwarding(userId='me', body=body).execute()
        print(result_update)
# Handle errors if there are
except errors.HttpError as err:
    print('\n---------------You have the following error-------------')
    print(err)
    print('---------------You have the following error-------------\n')

我提供给您的代码来自 Managing Forwarding (the same link you shared), you can also check the Users.settings.forwardingAddresses and the Python API library 有关 Gmail API 库和其中包含的端点的更多信息。

通知

您在另一个答案的评论之一中提到,在使用 .with_subject(arg) 时,您收到错误消息“用户没有权限”。勾选 OAuth: Managing API client access,它会为您提供一些步骤,以在您使用服务帐户和 G Suite 时启用所需的授权。