【发布时间】:2021-03-02 23:16:00
【问题描述】:
我有一个用 python 开发的应用程序,它使用 SMPT 服务连接到一个 gmail 帐户。这种类型的连接被称为“访问不安全的应用程序”lesssecureapps。
为了解决这个问题,我为自己设定了更新我的应用程序的任务,使用 gmail api 并使用从服务帐户生成的私钥进行身份验证(不使用 G-Suit)。
我已经创建了第一个概念证明,它似乎可以正确连接和验证,但是在尝试获取 gmail 帐户的标签时,我收到以下消息:
<HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Precondition check failed.">
我回顾一下我配置我的谷歌帐户所遵循的步骤:
- 我访问Google Api Console 并通过顶部显示的按钮启用 gmail api 的使用:启用 api 和服务
- 我访问凭据部分,单击顶部按钮:“创建凭据”并选择服务帐户
- 我创建一个服务帐号,然后生成一个json格式的私钥
我在我的概念证明中添加了一个小代码 sn-p,它返回了我在顶部评论的错误:
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://mail.google.com/','https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.labels','https://www.googleapis.com/auth/gmail.metadata','https://www.googleapis.com/auth/gmail.addons.current.message.metadata','https://www.googleapis.com/auth/gmail.addons.current.message.readonly']
SERVICE_ACCOUNT_FILE = '/home/user/keys/privatekey_from_service_account.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('gmail', 'v1', credentials=credentials)
# Call the Gmail API
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No tienes labels.')
else:
print('Labels:')
for label in labels:
print(label['name'])
如何在不使用 g-suite 的情况下解决我的问题?
【问题讨论】:
标签: python-3.x google-api gmail-api google-api-python-client service-accounts