我想在我的应用程序中使用 gmailAPI 来使用自动转发功能,因为我是 API 的新手,所以我按照 python 快速入门指南中给出的步骤进行操作,然后我进行了如下操作
首先我去了:- https://developers.google.com/gmail/api/quickstart/python?authuser=0并按照那里的所有步骤打开 gmail API 并将 credentials.JSON 文件复制到工作目录并在系统上安装 python 包并复制代码。 然后我将范围编辑为:- https://www.googleapis.com/auth/gmail.settings.sharing 以便转发设置可用。 然后我使用以下方法编辑了代码:- https://developers.google.com/gmail/api/guides/forwarding_settings 最终代码如下所示:-
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/gmail.settings.sharing']
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
address = { 'forwardingEmail': '<forwarding_mailid>' }
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'
}
result = service.users().settings().\
updateAutoForwarding(userId='me', body=body).execute()
if __name__ == '__main__':
main()
它说转发邮件也应该被验证所以我在 gmail 的转发设置中验证了帐户中的“
然后我在系统上运行脚本然后它要求登录所以我登录帐户然后脚本运行并且控制台产生了这个错误:-
googleapiclient.errors.HttpError:
错误在这一行:- “创建(userId='我',body=address)。执行()”
在每个 senario 中,我在同一行遇到相同的错误,即在生成“结果”时。 我无法理解我在什么地方做错了什么,或者我是否忘记了中间的一些步骤。
最佳答案
您需要一个具有全域权限的服务帐户:
作为您收到的错误和 updateAutoForwarding明确说明,您需要使用具有全域权限的服务帐户才能更新自动转发设置:
This method is only available to service account clients that have been delegated domain-wide authority.
重要提示:您需要是域管理员才能向服务帐户授予域范围的权限。因此,如果您不是管理员,则无法通过 API 管理自动转发。
因此您必须创建一个服务帐户,授予它域范围的权限,并使用它来模拟一个普通帐户:
检查 this有关什么是服务帐户的概述:特别是 this section如何创建它们和this one用于委派全域权限。
成功设置服务帐户后,您必须更改在代码中构建凭据的方式,如下所示:
creds = service_account.Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
creds = creds.with_subject('impersonated_account@your_domain.com')
其中 credentials.json
是为服务帐户下载的 JSON
文件,impersonated_account@your_domain.com
是您想要的电子邮件地址要模拟的服务帐户。
引用:
关于python - 使用 GmailAPI 在帐户设置中添加自动转发时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63168307/