How to send an email using GMAIL API in Python

Hello Guys! In this tutorial, you will learn how to send an email using Gmail API in python. We can automate our emails using GMAIL API.

To send an email you will need to follow the below steps. If you are new to work with APIs, please check out this tutorial before proceeding further.

Working with API’s In Python
  1. Create GMAIL API Credentials
  2. Get autherization token
  3. Send emails

1. Create GMAIL API Credentials:

First, you need to create a google cloud account, it’s absolutely free. Now create a new project with a proper name.

Now you need to enable the GMAIL API. Before that select your project which was created previously.

Enable API

Click on Enable APIs AND SERVICES to allow GMAIL API services. Now search for Gmail API on the search bar and click on Enable.

Now click on create credentials and give app name and developer email and then save and continue. In the end, you will get credentials in the JSON file. Download the credentials file and save it on the local folder in which you are working.

Once you got the credentials, you need to authorize and get the permissions to access the GMAIL API.

2. Get autherization Token:

Go to the Google API Docs, and select Python, You fill it in the left menu. once you click on it, you will get the source code.

Copy the source code and save it locally, make sure don’t use email / Gmail / cred when you save that python file, it may cause more errors.

Now change the SCOPES variable to “

Make sure you may save your credentials with the name credentials.json else change accordingly to the code.

Now create a virtual environment for installing the required modules to send an email using GMAIL API in Python.

Now save these below lines in a text file (.txt). You must have the Python > 3.6 version to avoid errors.


Now run the below command to install the above modules. if you saved the file as requirements.txt‘, then

pip install -r requirements.txt

Once you installed the modules, you will be good to execute the code which was copied and modified in the above. for better understanding I am giving that code here. please change according to your file names.

from __future__ import print_function
import os.path
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 = ['', '']
SCOPES =  ['']
def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    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:
            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)

    return service

service = main()

I saved the above file as

If you execute it will prompt your browser window and ask for the permissions. Please click the continue / allow button to accept it. At the end, it will create a token.json file in your directory.

Once you succeeded in generating the token.json file, you are good with the Next Step.

3. Send emails in Python

Copy the below script and save it locally in the same directory.

from auth import main
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

service = main()

def create_message(service,to, subject, message):

  emailMsg = message
  Message = MIMEMultipart()
  Message['to'] = to
  Message['subject'] = subject
  Message.attach(MIMEText(emailMsg, 'plain'))
  raw_string = base64.urlsafe_b64encode(Message.as_bytes()).decode()
  message = service.users().messages().send(userId='me', body={'raw': raw_string}).execute()
  return message

print(create_message(service,'<reciever>','Test email subject','This is a simple test email - message'))

Make sure with your file name, here I accessed my file as a module to send an email using GMAIL API in Python.

Give the subject of the email, message, and receiver email address to send an email. Now execute it.

It will send the email and print the JSON response in your command prompt.

Hope you successfully sent an email using GMAIL API in Python. If it is helpful or getting errors please feel free to comment below.

Thank you 🙂

Leave a Reply