Sending mail using Gmail API and Detailed Guide to Google APIs documentation.

Developervick
7 min readFeb 16, 2023

--

Photo by Solen Feyissa on Unsplash

We as a programmer have to work with multiple tools and technologies, libraries and APIs. To understand their working mechanism we spent lot of time reading their documentation some time its easy and some its head screeching which significantly impacts our productivity. In these particular cases we refer to articles and blogs to find the exact information to get our work done because Its not always possible to master all the tools and technologies or to reinvent the wheel. And here we have to take help of community.

In this article we are going to learn.

  1. Guide to Read documentation.
  2. Getting credentials.
  3. Getting Access token and Refresh token to authenticate our script with API.
  4. Setup code for Gmail API.
  5. Creating and sending first automated mail through gmail API.
  6. Understanding Google API’s documentation.

1. Guide to Read Documentation

Google APIs documentation is very large and reading it by yourself is little time consuming. So don’t worry I will guide you.

Google provides several libraries to efficiently use its APIs and services, a dedicated service called Google Discovery Service is used to provide all the information about all the APIs offered by google. So it will be our starting point.

To work with any Google’s API we must be familiar with terms used in documentation.

For our use we will discus about 3 necessary terms:

  1. Scopes: Scopes are same as permissions. Which are need to set at time of generating credentials to restrict and allow services for a particular client(user).
  2. Resource: Resource is the term used to describe collection of same type of entities and a single entity. Like in our case collection of Users in gmail is user resource. Same like drafted mails are draft resource.
  3. Methods: Methods are used to perform particular operation on resource or to access required resource.
Screenshot of drafts Resource documentation
Screenshot of Official Documentation.

2. Getting Credentials

To interact with any google API we required to have credentials to use google service. It can be a traditional API key and can be industry standard Oauth 2.0 Client Id and Client Secret credentials. In our case we will use Oauth 2.0 credentials.

Steps to generate credentials:

  1. Login to google cloud work space.
  2. Create a project and go to API & Services.
  3. Enable API, In our case we will enable gmail API.
  4. Now back to API & Services and Go to Oauth 2.0 consent screen.
  5. Now Go to Credentials > Create Credentials > Oauth 2.0 > Desktop App

** Web app Credentials will not work for App running on local Machine

6. Download JSON file and save it to the same directory where your script is stored. Woohhh !! now Let’s back to the code.

Below i have provided visual guide.

— —

Click to enable gmail API

— —

Choose External User type.

Try to leave everything as it is after this screen only fill required information and define scopes.

Add https://www.googleapis.com/auth/gmail/modify to send mail.

Generate Oauth Credentials and download JSON file and save it to same directory as “api_creds.json” file.

3. Getting Access token and Refresh token to Authenticate our script with API

Ohkk.. we have Credentials File which contains Client ID and Client Secret Now we need to get Access token and Refresh token for our script to actually interact with API.

Well a question will arise in your mind what are these tokens and why do we need them. In laymen terms, Client Id and Client Secrete are like password for admin user And access token and Refresh token are like password for our script. You can read more about it on Oauths official website.

The code below will do the rest of work for you. This code will generate a token.js file in your base directory which contains both tokens and necessary information to authenticate your script.

Python Code:

pip install --upgrade google-api-python-client google-auth-httplib2 
google-auth-oauthlib

Above command will install required libraries to run below code.

Importing libraries -

import os

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

Code to get access token and refresh token-

Function needs path of credentials.json file(api_creds.json) and list of scopes.

def get_token(path, scopes):

"""
This function returns token for google APIs and Services.

1. To create creds for our script, pass the path of credentials.json
file. Which is downloaded from google cloud console.

2. Pass scopes of your service to the scopes parameter as python list
object.

*** If you changes scopes and credentials and you recieve any
error than delete the existing token.js file and Re-run the code. So
it can create a fresh token.json file.

3. 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.

"""

PATH = path
SCOPES = scopes
token = None

# Checks for existing tokens.
if os.path.exists('token_creds.json'):
token = Credentials.from_authorized_user_file('token_creds.json',
SCOPES)

# If there are no (valid) tokens available, let it retieve new tokens.
if not token or not token.valid:
if token and token.expired and token.refresh_token:
token.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
PATH, SCOPES)
token = flow.run_local_server(port=0)

# Saves the credentials for later use.
with open('token_creds.json', 'w') as token:
token.write(token.to_json())

return token

Now we are all set to interact with Gmail API.

4. Setup code for Gmail API

Lets build a setup for Gmail API.

Code written below can be used to build setup for any Google API by changing parameters and modifying code according to requirements of specific Google’s service.

Basically We will build a function which returns a service. Service is like a last man with which we will interact with API’s server.


def get_service(token_creds):

try:
# Calls the Gmail API
service = build('gmail', 'v1', credentials=token_creds)
return service

except HttpError as error:
# Prints error if any
print(f'An error occurred: {error}')

5. Creating and Sending first automated mail through gmail API

To send a mail we requires a proper json object for mail information which is little fuzzy to create. So we will use email library.

pip install email
import base64
from email.message import EmailMessage

cred_file_path = "./api_creds.json"

scopes = ['https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.compose']

token_creds = get_token(cred_file_path, scopes)


def send_gmail_message(reciepent_id, subject,
message, service, sender_id="mymailid@gmail.com"):

"""
Creates and sends a basic email message
Return: Prints message ID and returns message object.
"""

msg = str(message)

try:
# Sets up message parameters.
message = EmailMessage()
message.set_content(msg)

message['To'] = reciepent_id
message['From'] = sender_id
message['Subject'] = subject

# encodes message
encoded_message = base64.urlsafe_b64encode(message.as_bytes()) \
.decode()

#creating message
create_message = {
'raw': encoded_message
}

# sending message
send_message = (service.users().messages().send
(userId="me", body=create_message).execute())
print(F'Message Id: {send_message["id"]}')

except HttpError as error:
print(F'An error occurred: {error}')
send_message = None

return send_message

if __name__ == '__main__':
send_gmail_message("myfriend@gmail.com", "Succces mail",
"myemailId@gmail.com", get_service(token_creds))

Hurray !! Check your inbox you have mail from your script.

6. Understanding Google APIs documentation.

Google APIs documentation have two important parts one is Guide section and other one is Reference section.

In our example we will take Gmail API’s documentation as refrence.

Guide section provides all the information about API and a quick start code.

Reference section provides full documentation about Client libraries, API’s json schema and developer related information.

Highlighted texts showing which service we should create. Use this information to create appropriate service for other APIs.

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

The hierarchy of sidebar showing methods to perform particular action.

Example code

# users.messages.send method will send a message.
service.users().messages().send(userId="me", body=json_body).execute()

# same like users.drafts.create method will create a draft message.
service.users().drafts().create(userId="me", body=json_body).execute()

Request body showing which json object should be passed in body parameter. Clicking on Message link will reveal json schema.

This is the valid json schema to create message which will be passed in body parameter for successful call.

7. Conclusion

We have sent mail from gmail API service. And understood the documentation of Gmail API. This guide can be used to understand almost all the google APIs.

--

--