Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

403 "Request had insufficient authentication scopes" when creating drafts in Google API with Python

I am working with the google api for the first time, and am new to coding in general, and have a question that I'm sure is very simple, but I cannot find the answer to. When I run the following code -

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)

results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])

if not labels:
    print('No labels found.')
else:
    print('Labels:')
    for label in labels:
        print(label['name'])


message_body = "This is the message"

message = {'message': message_body}

draft = service.users().drafts().create(userId='me', body=message).execute()

I am successfully able to list the labels in my gmail account, but the request to create a draft kicks back an error message "Request had insufficient authentication request". I found that creating drafts requires one of the following scopes:

  • https://mail.google.com/
  • https://www.googleapis.com/auth/gmail.modify
  • https://www.googleapis.com/auth/gmail.compose

but for the life of me, I cannot figure out what exactly that means or how to make that happen, though I've done my best to find this somewhere.

like image 493
James L Avatar asked Oct 21 '16 23:10

James L


2 Answers

You probably have a global variable SCOPES in you code with the value of https://www.googleapis.com/auth/gmail.readonly if you are following the Quickstart. These scopes are used when your users are redirected to Google in order to give you an access_token so you can read the contents of your user's gmail account.

In order to send drafts etc. you need one of the scopes you mentioned, e.g. https://mail.google.com/. Change your value of SCOPES to this string, and remove your credentials located at ~/.credentials/gmail-python-quickstart.json as outlined by the Quickstart in order to get new credentials that can do more than just read content.

like image 72
Tholle Avatar answered Nov 06 '22 22:11

Tholle


I also found that in your working directory, you need to delete the token.pickle file, and then replace the SCOPES variable with one of these depending on your purposes. So, for example, if you're trying to send an email, use

SCOPES = ['https://www.googleapis.com/auth/gmail.send']
like image 3
ltjds Avatar answered Nov 06 '22 20:11

ltjds