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.

  • make sure your project is selected
  • go to navigation bar > APIs & Services > Library
  • 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
  • go to navigation bar > APIs & Services > Credentials
  • create OAuth Client Id

Ready to use Gmail API

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

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