In this guide, we will explore the Gmail API using Python and discover how to leverage Gmail APIs to execute various operations within Gmail, including sending emails, searching through emails, and deleting emails, among others. To accomplish this, we will begin by configuring the Gmail API in our Python script. First, let’s provide a brief overview and foundational introduction to the Gmail API.
Gmail APIs
Gmail stands out as the leading email service in the contemporary landscape, utilized by nearly everyone, including numerous organizations. In recent years, a variety of Gmail functionalities have been improved through the integration of artificial intelligence, which includes features such as composing suggestions and enhanced security measures aimed at identifying fraudulent and spam emails.
The Gmail API is a collection of RESTful APIs that enables users to engage with their Gmail accounts. It facilitates the utilization of its functionalities through Python scripting.
Prerequisites of Using Gmail APIs in Python
We must fulfil the following requirements for using Gmail APIs in our Python script:
- We should have a Python version higher or equal to 2.6.
- We must have a google account with Gmail service enabled of it.
- The system must be installed BeautifulSoup library (if not, then we should use 'pip install bsp' syntax in the command terminal to install it in our device).
- We should have basic knowledge of Google OAuth libraries and Google API client.
Installation of Required libraries:
Prior to activating the Gmail APIs for utilization within our Python script, we must first install the necessary libraries on our system. To set up the required libraries for enabling the Gmail APIs, please adhere to the subsequent steps:
Step 1: Launch the command prompt terminal on your computer and verify that your device is connected to the internet.
Step 2: Enter the subsequent command into the terminal:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
At this point, hit the enter key to initiate the process of library installation.
As observed, the necessary libraries for activating Gmail APIs have been successfully set up in our system. We can now move forward to the section of this tutorial that focuses on enabling Gmail APIs.
Enabling Gmail APIs in our device
To activate the Gmail APIs on our device, allowing us to utilize these APIs within our Python script, we must adhere to the subsequent steps:
Step 1: Initiating a New Project on the Google Cloud Console:
At this stage, the initial task is to sign into the Google Cloud Console (https://console.cloud.google.com/?pli=1) using your Google account credentials. Following the login, you will need to select the 'New Project' option to initiate the process of creating a new project.
If we possess a pre-existing project, we can also proceed with that ongoing project.
Step 2: Next, we need to navigate to the API and services section from the Project menu that we have established.
Step 3: At this point, you will notice the option labeled 'Enable Gmail API and services.' It is necessary to select this option in order to activate the Gmail APIs for your project.
Step 4: Configuration of Consent screen:
At this stage, we will set up the consent screen for the project we established by selecting the 'OAuth Consent Screen' option available in the menu. This option will only be visible if the consent screen has not yet been configured.
Step 5: At this stage, we need to specify the name of the application we desire and proceed to save the project.
Step 6: At this point, select the credentials option and navigate to the credentials section.
Step 7: Creating an OAuth Client ID:
At this point, we select the 'create credentials' option and proceed to the OAuth Client ID section to initiate its creation.
We perform this by following the below sequential procedure to create a new OAuth Client ID for our project:
- First, we choose the application type as the desktop application for the project.
- After that, we enter the application name (can be the same as we have set in the above steps or can be different) and click on the create button.
- Now, the OAuth client ID will be created for our project, and we download it and save it with the 'credentials.json' name and format for future references.
At this point, we have completed all the necessary procedures to activate the Gmail APIs, and we are ready to implement Gmail APIs within our Python script.
Note: We have to save the client ID and password so that we can use them in future references if required.
Importing Necessary Modules
At this point, we have configured all required APIs, and it's time to proceed with the importation of all essential modules. Below, we will examine an example that demonstrates how to import these modules.
Example -
# Importing os and pickle module in program
import os
import pickle
# Creating utils for Gmail APIs
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# Importing libraries for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# Importing libraries for dealing with the attachment of MIME types in Gmail
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from mimetypes import guess_type as guess_mime_type
# Request all access from Gmail APIs and project
SCOPES = ['https://mail.google.com/']
OurEmailID = 'OurMail@gmail.com' # giving our Gmail Id
# using a default function to authenticate Gmail APIs
def authenticateGmailAPIs():
creds = None
# Authorizing the Gmail APIs with tokens of pickles
if os.path.exists("token.pickle"): # using if else statement
with open("token.pickle", "rb") as token:
creds = pickle.load(token)
# If there are no valid credentials available in device, we will let the user sign in manually
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('client_secret_107196167488-dh4b2pmpivffe011kic4em9a4ugrcooi.apps.googleusercontent.com.json', SCOPES) # downloaded credential name
creds = flow.run_local_server(port=0) # running credentials
# Save the credentials for the next run
with open("token.pickle", "wb") as token:
pickle.dump(creds, token)
return build('Gmail', 'v1', credentials=creds) # using Gmail to authenticate
# Get the Gmail API service by calling the function
service = authenticateGmailAPIs()
Output:
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=107196167488-dh4b2pmpivffe011kic4em9a4ugrcooi.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A55991%2F&scope=https%3A%2F%2Fmail.google.com%2F&state=kfXlNyjvbKetyUK0op7OF9WY7shrKS&access_type=offline
Explanation -
Upon executing the previously provided program, an option to select a browser will appear, as illustrated in the image above. If such an option is not visible, it is necessary to click on the link presented in the output. This action will allow us to choose either our preferred browser or the system's default browser to proceed with the operation. Once we make our browser selection, we will be redirected to that browser, where we will observe the following tab open:
At this point, we will check the box presented in the dialog to grant the necessary permissions. Subsequently, we must select the continue option. Upon clicking continue, the subsequent window will appear within the same tab:
As displayed in the window, the authentication process for activating the Gmail API has been finalized, and we have successfully associated our Gmail account with the project designated for the Gmail APIs that we established.
Note: Of course, we have to put our mail that we can connect to Gmail APIs and use for future references for working with Gmail APIs, in the place of ' [email protected] ' as provided in the above program.
Performing Actions using Gmail APIs in Python
At this stage, we have successfully configured and activated the Gmail APIs within our project using a Python script. This enables us to execute a variety of operations directly from our Gmail account through a Python application.
We can perform the following Gmail actions with our Python script using Gmail APIs in it:
- Sending an email
- Searching an email
- Deleting an email or entire emails history
- Reading an email
- Marking read/unread an email etc.
In this guide, we will focus solely on the process of sending an email through Gmail APIs within a Python application. We will explore how to craft the necessary code to execute this functionality using a Python script.
Sending an email
We can effortlessly compose and dispatch an email by developing a Python script that utilizes the activated Gmail APIs. In this segment, we will create a Python program that allows us to send emails directly from our Gmail account with just the execution of the script.
Examine the subsequent Python program to gain a clearer comprehension of its functionality:
Example:
# importing os and pickle module in program
import os
import pickle
# Creating utils for Gmail APIs
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# Importing libraries for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# Importing libraries for dealing with the attachment of MIME types in Gmail
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from mimetypes import guess_type as guess_mime_type
# Request all access from Gmail APIs and project
SCOPES = ['https://mail.google.com/'] # providing the scope for Gmail APIs
OurEmailID = 'OurMail@gmail.com' # giving our Gmail Id
# using a default function to authenticate Gmail APIs
def authenticateGmailAPIs():
creds = None
# authorizing the Gmail APIs with tokens of pickles
if os.path.exists("token.pickle"): # using if else statement
with open("token.pickle", "rb") as token:
creds = pickle.load(token)
# if there are no valid credentials available in device, we will let the user sign in manually
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('client_secret_107196167488-dh4b2pmpivffe011kic4em9a4ugrcooi.apps.googleusercontent.com.json', SCOPES) # downloaded credential name
creds = flow.run_local_server(port=0) # running credentials
# save the credentials for the next run
with open("token.pickle", "wb") as token:
pickle.dump(creds, token)
return build('gmail', 'v1', credentials=creds) # using Gmail to authenticate
# Get the Gmail API service by calling the function
ServicesGA = authenticateGmailAPIs()
# Using a default funnction to add attachments in Mail
def AddAttachment(mail, NameofFile):
content_type, encoding = guess_mime_type(NameofFile)
if content_type is None or encoding is not None: # defining none file type attachment
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text': # defining text file type attachment
fp = open(NameofFile, 'rb') # opening file
msg = MIMEText(fp.read().decode(), _subtype = sub_type)
fp.close()
elif main_type == 'image': # defining image file type attachment
fp = open(NameofFile, 'rb')
msg = MIMEImage(fp.read(), _subtype = sub_type)
fp.close()
elif main_type == 'audio': # defining audio file type attachment
fp = open(NameofFile, 'rb')
msg = MIMEAudio(fp.read(), _subtype = sub_type) # reading file
fp.close()
else:
fp = open(NameofFile, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close() # closing file
NameofFile = os.path.basename(NameofFile)
msg.add_header('Content-Disposition', 'attachment', NameofFile = NameofFile)
mail.attach(msg) # composing the mail with given attachment
# Creating mail with a default function
def CreateMail(RecieverMail, SubofMail, BodyofMail, attachments=[]): # various import content of mail as function's parameter
# Using if else to check if there is any attachment in mail or not
if not attachments: # no attachment is given in the mail
mail = MIMEText(BodyofMail) # Body of Mail
mail['to'] = RecieverMail # mail ID of Reciever
mail['from'] = OurEmailID # our mail ID
mail['subject'] = SubofMail # Subject of Mail
else: # attachment is given in the mail
mail = MIMEMultipart()
mail['to'] = RecieverMail
mail['from'] = OurEmailID
mail['subject'] = SubofMail
mail.attach(MIMEText(BodyofMail))
for NameofFile in attachments:
AddAttachment(mail, NameofFile)
return {'raw': urlsafe_b64encode(mail.as_bytes()).decode()}
# Creating a default function to send a mail
def SendMail(ServicesGA, RecieverMail, SubofMail, BodyofMail, attachments=[]):
return ServicesGA.users().messages().send(
userId = "me",
body = CreateMail(RecieverMail, SubofMail, BodyofMail, attachments)
).execute() # Body of the mail with execute() function
# Sending an email by adding important content, i.e., Reciever's mail, Subject, Body, etc.
SendMail(ServicesGA, "Reciever@gmail.com", "Python Project i.e., This is the subject of Mail we are sendimg!",
"Now, this is the body of the email we are writing and we can add only written text here!", ["test.txt", "client_secret_107196167488-dh4b2pmpivffe011kic4em9a4ugrcooi.apps.googleusercontent.com.json"]) # calling out default SendMail() function
Output:
By substituting our email address in place of the recipient's email, such as [email protected], we will discover that the email is indeed directed to the address we specified as the receiver when we execute the program. This behavior is consistent with the output displayed in the image above.
Conclusion
In summary, to utilize the Gmail APIs within our Python script or directly in Python, it is necessary to activate these APIs and establish a Project in Google Cloud using our Gmail account.
In addition to sending emails, our Python program can execute a variety of other tasks using the Gmail APIs, such as reading messages, deleting emails, and more. Moreover, we have the capability to alter various aspects of our Gmail account that we have authenticated through our Gmail APIs project, all by executing our Python scripts that are configured with Gmail APIs.