HttpError 400 在使用服务帐户进行 users().messages().list Gmail API 调用期间先决条件检查失败

Afi*_*fiz 10 google-api gmail-api

我正在使用服务帐户在我的 Gmail 邮箱中列出消息,但是在调用此 API 时出现以下错误service.users().messages().list(userId='me').execute()

    HttpError                                 Traceback (most recent call last)
<ipython-input-44-da1dc3cccc81> in <module>
     27 
     28 apiservice = build('gmail', 'v1', credentials=service_cred)
---> 29 response = apiservice.users().messages().list(userId='me').execute()

~/opt/anaconda3/lib/python3.7/site-packages/googleapiclient/_helpers.py in positional_wrapper(*args, **kwargs)
    128                 elif positional_parameters_enforcement == POSITIONAL_WARNING:
    129                     logger.warning(message)
--> 130             return wrapped(*args, **kwargs)
    131         return positional_wrapper
    132 

~/opt/anaconda3/lib/python3.7/site-packages/googleapiclient/http.py in execute(self, http, num_retries)
    849       callback(resp)
    850     if resp.status >= 300:
--> 851       raise HttpError(resp, content, uri=self.uri)
    852     return self.postproc(resp, content)
    853 

HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages?alt=json returned "Precondition check failed.">
Run Code Online (Sandbox Code Playgroud)

代码:

scopes = [
    "https://mail.google.com/",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.labels",
    "https://www.googleapis.com/auth/gmail.metadata",
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
]

service_cred = service_account.Credentials.from_service_account_info(
                credentials, scopes=scopes)

service = build('gmail', 'v1', credentials=service_cred)
response = service.users().messages().list(userId='me').execute()
Run Code Online (Sandbox Code Playgroud)

use*_*234 10

当我尝试列出我的个人电子邮件中的电子邮件时,我也遇到了这个问题。启用 Gmail API 时,Google 仪表板为我设置了服务帐户凭据,因此我认为这就是我应该使用的。

\n

为了让 400 错误消失,我必须添加:

\n
delegated_credentials = credentials.with_subject(\'my-email@gmail.com\')\n
Run Code Online (Sandbox Code Playgroud)\n

请参阅https://developers.google.com/identity/protocols/oauth2/service-account#authorizingrequests

\n

\xc2\xa0

\n

但是,我随后收到错误消息,表明我的服务帐户未经授权无法代表我的个人电子邮件发出请求。如果您不使用 G Suite,我认为没有办法代表用户使用服务帐户。

\n

因此,我的问题的最终解决方案是使用 OAuth 身份验证,如Python 快速入门中所示。

\n

  • “如果您不使用 G Suite,我认为没有办法代表用户使用服务帐户。”我想我正在经历艰难的过程。不知道为什么他们没有在任何地方提到这一点。 (4认同)
  • 非常感谢您抽出时间并回复。是的,您是正确的,使用“with_subject”方法模拟用户帐户解决了该问题。我在他们的文档中找到了它,但不太容易找到。https://developers.google.com/identity/protocols/oauth2/service-account#python (3认同)