python-3.x - 通过服务器端的服务帐户使用 gmail api,避免使用 OAUTH2 GUI
问题描述
我有一个用 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 控制台并通过顶部显示的按钮启用 gmail api 的使用:启用 api 和服务
- 我访问凭据部分,单击顶部按钮:“创建凭据”并选择服务帐户
- 我创建一个服务帐户,然后生成一个 json 格式的私钥
我用我的概念证明添加了一个小代码片段,它返回了我在顶部评论的错误:
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 的情况下解决我的问题?
解决方案
“前置条件检查失败。”
意味着你不能做你想做的事。
使用从服务帐户生成的私钥(不使用 G-Suit)。
Gmail api 不支持非 gsuite 域的服务帐户。您只能使用具有 Gsuite 域帐户和 gsuite 域电子邮件的服务帐户。
服务帐户无法与普通的 google gmail 帐户一起使用。
推荐阅读
- html - 在可调整大小的输入右侧添加复选框
- python - 正则表达式作为列表项
- python - 从自上而下的相机确定多边形表面旋转的方法
- python - weakref.proxy 和weakref.ref 之间的区别?
- azure - Azure 中的 SQL 始终加密
- reactjs - 在 React 中设置 Material UI 的 TextField 组件的默认值
- r - 将多列数字数据转换为R中的日期
- python - 如何删除子目录中早于 x 天且未在 Python 中于周日创建的所有文件
- ios - 当 API 使用 MVVM 完成时重新加载 TableView
- typescript - 打字稿嵌套类型变量