【问题标题】:Can't authenticate Google service account to Gmail无法向 Gmail 验证 Google 服务帐户
【发布时间】:2019-01-23 16:08:21
【问题描述】:

我有一个 GSuite 电子邮件地址 example@gmail.com,并且我创建了一个 Google 服务帐户 example-sa@iam.gserviceaccount.com。

我的目标是从这个 SA 发送电子邮件,就好像它是电子邮件一样,但我无法验证 SA。

但是,我可以使用此代码登录服务帐户 Google Drive:

from google.oauth2 import service_account
from googleapiclient import discovery

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = 'sa-credentials.json'
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = discovery.build('drive', 'v3', credentials=creds, cache_discovery=False)

# code

但是,当我尝试对 gmail 执行相同操作时,出现错误:

from google.oauth2 import service_account
from googleapiclient import discovery

SCOPES = ['https://mail.google.com/']
SERVICE_ACCOUNT_FILE = 'sa-credentials.json'
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = discovery.build('gmail', 'v1', credentials=creds, cache_discovery=False)

profile = service.users().getProfile(userId='me').execute()

错误:

    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/profile?alt=json returned "Bad Request">

如果我点击错误消息中提供的 URL,我会得到:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

【问题讨论】:

    标签: python gmail-api google-api-client google-oauth service-accounts


    【解决方案1】:

    看到这个类似的问题:GMail API - Can I send email using the Service Account?

    没有。 Gmail API 适用于 Gmail 用户,服务帐户仅适用于 对真实的 Gmail 帐户进行身份验证,他们没有自己的 Gmail 帐号

    换句话说,服务帐户似乎不是您可以访问的 Gmail 邮箱。

    您需要使用服务帐户访问某个其他邮箱,为此,您需要做以下两件事之一:

    1. 使用 Oauth2 流获取您希望用来授予访问权限的邮箱的所有者(请参阅:https://developers.google.com/gmail/api/auth/web-server

    1. 如果您控制/拥有 Gsuite 域,请将该域的域范围权限授予您的服务帐户。见:https://developers.google.com/admin-sdk/directory/v1/guides/delegation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 2014-09-12
      • 2020-04-22
      • 1970-01-01
      相关资源
      最近更新 更多