Gmail Api return Unauthorized client or scope in r

2019-03-03 17:08发布

问题:

I have struggled to make this work but did half the job.

Actually I can only read messages from Gmail API, If I try to use the gmail.modify Scope I get an error:

HttpAccessTokenRefreshError: unauthorized_client: Unauthorized client or scope in request.

Here is my code:

# init gmail api
credentials_path = os.path.join(settings.PROJECT_DIR, 'settings/gmail_credential.json')
scopes = ['https://www.googleapis.com/auth/gmail.readonly',
          'https://www.googleapis.com/auth/gmail.modify']
credentials = ServiceAccountCredentials.from_json_keyfile_name(credentials_path, scopes=scopes)
delegated_credentials = credentials.create_delegated('my_account@gmail.com')
http_auth = delegated_credentials.authorize(Http())
gmail = build('gmail', 'v1', http=http_auth)

In my service account:

  • I have set all possibles rôles to my service account "......iam.gserviceaccount.com"
  • I activated DWD: DwD: Google Apps Domain-wide Delegation is enabled.

I have read somewhere that I need a google work account to give permission to my service account to use gmail.Modify on my my_account@gmail email account. Seems very hard way to just modify a message in an email.

I don't know what to do next.

回答1:

Based from this documentation, you need to use the client ID from your "Developers Console" as the Client Name in the "Manage API client access" when you're setting your API scopes. Google API does not work as expected with your personal account @gmail.com. You should have organization domain account in Google in format you@your_organisation_domain.

Check these threads:

  • Google API Python unauthorized_client: Unauthorized client or scope in request
  • Google API OAuth2, Service Account, "error" : "invalid_grant"