Gmail API - Python 中的自动转发



我一直在尝试让它工作一段时间,但我无法传递我得到的这个错误代码。

我使用此代码的目标是在gmail中设置转发电子邮件地址。以下是谷歌文档: 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">

错误的请求是迄今为止最令人沮丧的错误代码。我使用的是具有全域委派的服务帐户,因此我认为这不是权限问题。我已经复制了代码,所以很难相信 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()

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

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')

我基于我从管理转发(与您共享的相同链接(中为您提供的代码,您还可以检查 Users.settings.forwardingAddresses和Python API 库 ,详细了解 Gmail API 库及其包含的端点。

通知

您在另一个答案的一条评论中提到,使用.with_subject(arg)时,您会收到错误"用户没有权限"。 选中 OAuth:管理 API 客户端访问权限,它将为您提供一些步骤,以启用您使用服务帐号和 G Suite 时所需的授权。

您使用的是无权访问 Gmail 的服务帐号。

您可以使用服务帐户模拟 GSuite 用户,也可以使用 OAuth 直接以用户身份登录。

最新更新