python - 无法向 Gmail 验证 Google 服务帐户的身份

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

我有一个 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"
 }
}

最佳答案

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

No. The Gmail API is for Gmail users and service accounts are just for doing auth to a real Gmail account, they don't have their own Gmail account, etc.

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

您需要使用服务帐户访问某些其他邮箱,为此,您需要执行以下两项操作之一:

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

或者

  • 如果您控制/拥有 Gsuite 域,请向您的服务帐号授予该域的域范围权限。请参阅:https://developers.google.com/admin-sdk/directory/v1/guides/delegation
  • 关于python - 无法向 Gmail 验证 Google 服务帐户的身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51881430/

    相关文章:

    gmail-api - 关于原始查询参数的困惑

    ios - 我如何通过适用于 iOS 的 GoogleAPIClientForREST 授权和上传视频

    android - 使用 FusedLocationProviderClient 进行位置更新会产生内存泄漏

    google-analytics - HTTP 请求和记录在案的 Google Analytics API 调用之间的区别

    python - (Python) 平均分配数字

    python - 我们可以替换来自 sympy.Function 变量微分的 sympy 中的 'Derivative' 项吗?

    java - 原子文件写入操作(跨平台)

    java - 如何使用 Java 运行带参数的 python 代码,./AdafruitDHT.py 22 4

    google-apps-script - 如何获取所有附有特定标签的草稿消息

    javascript - Gmail Apps 脚本函数显示来自 GMail Addon 的浏览器 MsgBox