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 “https://www.googleapis.com/auth/gmail.send

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.

beautifulsoup4==4.9.3
cachetools==4.2.2
certifi==2021.5.30
charset-normalizer==2.0.4
google==3.0.0
google-api-core==2.0.0
google-api-python-client==2.18.0
google-auth==2.0.1
google-auth-httplib2==0.1.0
google-auth-oauthlib==0.4.5
google-cloud-core==2.0.0
google-cloud-translate==3.3.2
googleapis-common-protos==1.53.0
grpcio==1.39.0
httplib2==0.19.1
idna==3.2
oauthlib==3.1.1
packaging==21.0
proto-plus==1.19.0
protobuf==3.17.3
pyasn1==0.4.8
pyasn1-modules==0.2.8
pyparsing==2.4.7
requests==2.26.0
requests-oauthlib==1.3.0
rsa==4.7.2
six==1.16.0
soupsieve==2.2.1
uritemplate==3.0.1
urllib3==1.26.6

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 = ['https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.labels']
SCOPES =  ['https://www.googleapis.com/auth/gmail.send']
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:
            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)

    return service


service = main()


I saved the above file as auth.py

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>@email.com','Test email subject','This is a simple test email - message'))

Make sure with your file name, here I accessed my auth.py 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