无法向 Gmail 验证 Google 服务帐户

Can't authenticate Google service account to Gmail

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

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

但是我可以登录服务帐户 Google 使用此代码驱动器:

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

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