无法将Google服务帐户验证为Gmail [英] Can't authenticate Google service account to Gmail

查看:226
本文介绍了无法将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:

  1. 使用Oauth2流获取您要用于授予访问权限的邮箱的所有者(请参阅: https://developers.google.com/gmail/api/auth/网络服务器)

  1. 如果您控制/拥有Gsuite域,请将该域的整个域范围的权限授予您的服务帐户.请参阅: https://developers.google.com/admin-sdk/目录/v1/guides/委托

这篇关于无法将Google服务帐户验证为Gmail的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆