Skip to content
Advertisement

Is it possible to use the Python requests library to send Gmail only using the Google Gmail API

Is it possible to use the Python requests library to send Gmail only using the Google Gmail API? I am trying to send Gmail with a python request library. But it ends up with an error 401. I want to know what is the proper way to send Gmail with Google Gmail API.

import sys
import requests
import base64
import sys
from email.mime.text import MIMEText

AccessToken = ""

params = {
        "grant_type":    "refresh_token",
        "client_id":     "xxxxxxxxxxxxxxx",
        "client_secret": "xxxxxxxxxxxxxxx",
        "refresh_token": "xxxxxxxxxxxxxxxxxxxx",
        }

authorization_url = "https://www.googleapis.com/oauth2/v4/token"

r = requests.post(authorization_url, data=params)

if r.ok:
    AccessToken = str((r.json()['access_token']))

EmailFrom = "Test1@gmail.com"
EmailTo = "test2@gmail.com"

def create_message(sender, to, subject, message_text):
   
    message = MIMEText(message_text, 'html')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    body = {'raw': raw}
    return body


body  = create_message(EmailFrom, EmailTo, "Just wanna Say Waka Waka!", "Waka Waka!")


url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"

header = {
    'Authorization': 'Bearer ' + AccessToken,
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}

r = requests.post(
    url,
    header,
    body
)

print(r.text)

Advertisement

Answer

There is an example on in the documentation for sending with python You should consider using the Python Client library instead of coding this yourself.

def create_message(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())}
Advertisement