Sending Email with Python using Gmail API

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 scope and update
  • 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 = ['']

creds = None
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:
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:

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
{'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

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

message = create_message('me',, '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




Learning javascript and web-development

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Introduction Bluetooth Low Energy Mesh

TripGo API — Special features

Building Stevie the Robot’s​ AI

Creating “Hello World “Spring Boot Project with STS and Maven Part 1

Overlays are not the solution to your accessibility problem

Linear Gauge Widget In Flutter

CS373 Fall 2020: Jesse Huang

Welcome to MS IT Institute: Where IT Leaders are Created

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cho Zin Thet

Cho Zin Thet

Learning javascript and web-development

More from Medium

Build your own QRCode using Python

Automatically push source code to a GitHub repository

How to upgrade Ubuntu by using CLI

CherryPy- A Python Web Framework