Sending Email with Python using Gmail API

Cho Zin Thet
3 min readSep 30, 2021
vecteezy image

Preparing in Google Cloud Console,

For some api, we need to create api key to use their products and pass api key every time we request to their api. In the same way to use google api, we need to create some secret key. There are so many google api and we need to create a project and enable api that we want to use and create oauth client id as our secret key.

Create Project

Enable API

  • make sure your project is selected
  • go to navigation bar > APIs & Services > Library

Creating OAuth Consent Screen

  • go to navigation bar > APIs & Services > OAuth Consent Screen
  • create OAuth Consent Screen
  • add https://mail.google.com/ scope and update
add https://mail.google.com
  • add test user
  • check test user and scopes in summary section

Creating OAuth ClientId

  • go to navigation bar > APIs & Services > Credentials
  • create OAuth Client Id

Add to your project folder and rename credentials.json

Ready to use Gmail API

Send Email

from __future__ import print_function
import base64
import os.path
from email.mime.text import MIMEText
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://mail.google.com/']

creds = None
if
os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())


service = build('gmail', 'v1', credentials=creds)


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


def send_message(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print('Message Id: %s' % message['id'])
return message
except
Exception as error:
print(error)


message = create_message('me', john@gmail.com, 'hello', 'testing 123')
print(send_message(service=service, user_id='me', message=message))

you need to replace receiver email in create_message function

  • to authorize user, this will redirect to sign in with google
  • sign in and verify app

This message will send to john@gmail.com

--

--