3

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
    Does that account actually have mail enabled? For example, if they signed up a Google Account with their yahoo address (and didn't create a gmail account), or it's a Google Apps for Work user where Mail service isn't enabled then that could cause that error. Easy way to test is for the account to login to https://mail.google.com in a browser. – Eric D Mar 27 '15 at 19:51
  • Yes. I'm testing it on my own account. I tried it via google's api explorer also and it works there. In the code sample above `client_email` is email address that's listed under the API section on the dev console page. – Tadas Vilkeliskis Mar 27 '15 at 20:09

1 Answers1

6

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.

Jay Lee
  • 13,415
  • 3
  • 28
  • 59
  • 2
    Thank you. This helped. I tried it before but I didn't have my security settings updated to allow client access to the account. The error message is very misleading since I wasn't getting auth error. – Tadas Vilkeliskis Mar 28 '15 at 17:36