无法将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"
}
}
查看类似的问题:
不. Gmail API适用于Gmail用户,服务帐户仅适用于
对真实的Gmail帐户进行身份验证,他们没有自己的Gmail
帐户等.
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邮箱. In other words, the service account doesn't appear to be a Gmail mailbox that you can access. 您需要使用服务帐户访问某些 other 邮箱,并且要执行此操作,您需要执行以下两项操作之一: You need to use the service account to access some other mailbox, and to do that, you need to do one of two things: 或