7
votes

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:

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.

3

3 Answers

12
votes

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.

2
votes

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']
0
votes

example for the quickstart code with Ruby using gem google/apis/gmail_v1 (scope readonly seems to be mandatory but additional scopes can be added):

SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_READONLY, Google::Apis::GmailV1::AUTH_GMAIL_COMPOSE

Remove the tokenfile (token.yaml) before running quickstart.rb and make sure you are in the directory where it is located. When you go to the link which is generated, you will be asked to approve access for each scope seperately.

In case there are errors with the scope after generating the token (eg scope can not contain space), try the following syntax in your code

  SCOPE ||= [Google::Apis::GmailV1::AUTH_GMAIL_READONLY, Google::Apis::GmailV1::AUTH_GMAIL_COMPOSE]