无法将Google服务帐户验证为Gmail

问题描述:

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

I have a GSuite email address example@gmail.com and I created a Google service account example-sa@iam.gserviceaccount.com.

我的目标是从此SA发送电子邮件,就像发送电子邮件一样,但我无法对SA进行身份验证.

My goal is to send emails from this SA as if it was the email but I'm not able to authenticate the SA.

但是我可以使用以下代码登录服务帐户Google云端硬盘:

I could however login the service account Google Drive with this code:

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进行相同操作时,出现错误消息:

However, when I try to do the same for gmail I get an error:

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,则会得到:

If I click on the URL provided in the error message I get:

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