gmail api gives failedPrecondition error

浪尽此生 提交于 2019-12-19 04:13:44

问题


I can't get gmail api to work. I'm using server-to-server authentication with JWT.

google-api-python-client==1.4.0
httplib2==0.9
oauth2client==1.4.7
pycrypto==2.6.1

My code looks like this.

with open(CLIENT_SECRET_FILE) as f:
    data = json.loads(f.read())
    private_key = data['private_key']
    client_email = data['client_email']
    credentials = SignedJwtAssertionCredentials(client_email,   private_key, scope=OAUTH_SCOPE)

http = credentials.authorize(http)
gmail_service = build('gmail', 'v1', http=http)
try:
    threads =    gmail_service.users().messages().list(userId='me').execute()
except Exception as e:
    print e
    print e.content

The response is

<HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages?alt=json returned "Bad Request">
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "failedPrecondition",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }
}

Thanks.


回答1:


Try:

credentials = SignedJwtAssertionCredentials(client_email,
  private_key,
  scope=OAUTH_SCOPE,
  sub='user@yourdomain.com')

The sub= tells the Service Account which account you wish to impersonate. Without it, you're authenticating as the Service account user which, as Eric pointed out, doesn't have a Gmail mailbox.



来源:https://stackoverflow.com/questions/29307965/gmail-api-gives-failedprecondition-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!