首页 > 解决方案 > 通过服务器端的服务帐户使用 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.">

我回顾了配置我的谷歌帐户所遵循的步骤:

  1. 我访问Google Api 控制台并通过顶部显示的按钮启用 gmail api 的使用:启用 api 和服务
  2. 我访问凭据部分,单击顶部按钮:“创建凭据”并选择服务帐户
  3. 我创建一个服务帐户,然后生成一个 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 的情况下解决我的问题?

标签: python-3.xgoogle-apigmail-apigoogle-api-python-clientservice-accounts

解决方案


“前置条件检查失败。”

意味着你不能做你想做的事。

使用从服务帐户生成的私钥(不使用 G-Suit)。

Gmail api 不支持非 gsuite 域的服务帐户。您只能使用具有 Gsuite 域帐户和 gsuite 域电子邮件的服务帐户。

服务帐户无法与普通的 google gmail 帐户一起使用。


推荐阅读