1
votes

I'm trying to send an email using the Gmail API in python. I think I followed the relevant documentation and youtube vids.

I'm running into this error:

googleapiclient.errors.HttpError: HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Insufficient Permission"

Here is my script:


    #!/usr/bin/env python

    from googleapiclient.discovery import build
    from httplib2 import Http
    from oauth2client import file, client, tools
    from email.mime.text import MIMEText
    import base64
    import errors

    SCOPES = 'https://mail.google.com/'
    CLIENT_SECRET = 'client_secret.json'

    store = file.Storage('storage.json')
    credz = store.get()
    if not credz or credz.invalid:
        flags = tools.argparser.parse_args(args=[])
        flow = client.flow_from_clientsecrets(CLIENT_SECRET, SCOPES)
        credz = tools.run_flow(flow, store, flags)

    GMAIL = build('gmail', 'v1', http=credz.authorize(Http()))

    def CreateMessage(sender, to, subject, message_text):
      """Create a message for an email.

      Args:
        sender: Email address of the sender.
        to: Email address of the receiver.
        subject: The subject of the email message.
        message_text: The text of the email message.

      Returns:
        An object containing a base64url encoded email object.
      """
      message = MIMEText(message_text)
      message['to'] = to
      message['from'] = sender
      message['subject'] = subject
      return {'raw': base64.urlsafe_b64encode(message.as_string())}

    def SendMessage(service, user_id, message):
      """Send an email message.

      Args:
        service: Authorized Gmail API service instance.
        user_id: User's email address. The special value "me"
        can be used to indicate the authenticated user.
        message: Message to be sent.

      Returns:
        Sent Message.
      """
      try:
        message = (service.users().messages().send(userId=user_id, body=message)
                   .execute())
        print 'Message Id: %s' % message['id']
        return message
      except errors.HttpError, error:
        print 'An error occurred: %s' % error

    message = CreateMessage('[email protected]', '[email protected]', 'test_subject', 'foo')
    print message
    SendMessage(GMAIL, 'me', message)

I tried adding scopes, trying different emails, etc. I have authenticated by logging into my browser as well. (The [email protected] is a dummy email btw)

2

2 Answers

2
votes

Try deleting generated storage.json file and then try again afresh.

you might be trying this script with different scopes so "storage.json" might be having wrong details.

1
votes

I had the same problem.

I solved it by running again the quickstart.py that provides google and change SCOPE so that google can give you all permissions you want. After that don't need to have SCOPE or CLIENT_SECRET on your new code to send a message, just get_credentials(), CreateMessage() and SendMessage() methods.