Python interface for the Gmail API
In this tutorial, we are going to learn about the Gmail API in Python. In addition, we are going to learn how we can use the Gmail APIs in Python to conduct a variety of Gmail actions, such as sending an email, looking for an email, deleting an email, and many more. In order to do this, we will study how to configure the Gmail API in our Python application. To begin, let’s take a quick overview of the Gmail API and its fundamentals.
introduction.
Gmail APIs
Gmail is by far the most popular electronic mail service in the modern world, and the vast majority of businesses and individuals make use of it. Gmail has been using artificial intelligence to improve a wide variety of services over the last several years, including recommendations for when users are drafting emails and security safeguards (detecting fraud and spam emails).
Gmail API is an application programming interface (API) that is based on RESTful APIs. It enables its users to communicate with our Gmail account, and it enables us to access Gmail’s capabilities by using Python.
script.
Prerequisites of Using Gmail APIs in Python
In order to use Gmail APIs in our Python program, we need to satisfy the following prerequisites.
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:
Before we enable the Gmail APIs so that our Python script can make use of them, let’s make sure that our machine has all of the prerequisite libraries installed. The following are the actions that need to be taken in order for us to successfully install the pre-required libraries that are needed in order to enable the Gmail APIs: Step 1: Launch the command prompt terminal of the system and ensure that our device has an active internet connection. Step 2: In the space provided, jot down the following command:
terminal:
-
pip install –upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
At this time, hit the enter key to begin the installation of
libraries.
The essential libraries for enabling Gmail APIs have been successfully installed in our system, as we can see. This was a pre-requisite need. Now that this step has been completed, we can go on to enable the Gmail APIs.
tutorial.
Enabling Gmail APIs in our device
In order to utilize the Gmail APIs in our Python script, we need to activate them on our device by following the procedures outlined below, which can be found in the Google Cloud Console. Step 1: Establishing a New Project on the Google Cloud Console:
At this stage, we are required to first sign in to the Google cloud console using our Google account (https://console.cloud.google.com/?pli=1), and then we are required to click on the ‘New Project’ button in order to initiate the creation of a new project.
project.
If there is already a project in progress, then we may continue with that project if there is already one in progress. Step 2: At this point, we are required to go to the Project menu that we have and choose the API and services option.
created.
The third step is to activate Gmail APIs for the application. This may be done by selecting the “Enable Gmail API and services” option, which is now shown on the screen.
project.
The configuration of the consent screen is the fourth step.
Clicking on the ‘OAuth Consent Screen’ option that is shown in the menu will take us to the next phase of the process, in which we will set the consent screen for the project that we just established. This choice will only be visible to us if the consent screen has not yet been shown.
configured.
The fifth step requires us to choose a name for the application that we are developing and then save the project. Step 6: At this point, choose the credentials option, and then go to.
credentials.
The seventh step is to generate an OAuth Client ID.
Now, we go to the OAuth Client ID and create it by selecting the “create credentials” option from the drop-down menu.
In order to do this, we will generate a new OAuth Client ID for our company by completing the steps outlined below in sequential order.
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.
Now that we have completed all of the procedures necessary to enable Gmail APIs, we are ready to begin using Gmail APIs in our Python programs.
script.
Importing Required Modules with
Note: We have to save the client ID and password so that we can use them in future references if required.
Because we have now finished configuring all of the required APIs, we can go on to the next step, which is to import all of the required modules. Have a look at the example of importing modules that is provided below. 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
W01A9@@8 Explanation for W01A9@@8
If we don’t see an option like this when we run the program that was given to us above, we need to click on the link that was provided in the output. This option will appear on the screen for us to choose the browser when we run the program that was given to us above. After that, in order to proceed with the procedure, we may choose the web browser of our choosing or the one that is pre-installed on the device. Now, when we pick the browser, we will be sent to our browser, and we will be able to see the following tab opened in our browser:
it:
To provide the necessary rights, we must first ensure that the checkbox option shown in the dialogue box is selected, and after that, we must choose the continue option in order to proceed. After selecting continue from the drop-down menu, the following window will appear in the same location as before.
tab:
We have successfully connected our Gmail account with the project for Gmail APIs that we are working on, and the window that is appearing indicates that the authentication phase of activating Gmail API has been finished.
created.
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 ‘OurMail@gmail.com’ as provided in the above program.
Performing Actions using Gmail APIs in Python
At this point, we have finished integrating Gmail APIs into our app using Python script and have enabled them. With a Python application, we are now able to access our Gmail account and carry out a variety of tasks.
Using the use of Gmail APIs in our Python script, we are able to carry out the following Gmail operations:
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 lesson, we will solely discuss sending an email from our Python program by using the Gmail APIs, and we will learn how to construct the code that will enable us to carry out this activity using Python.
script.
Sending an email
By building a Python program and incorporating enabled Gmail APIs into it, it is possible for us to quickly compose and send an email. In this part of the tutorial, we will create a Python program that, when executed, will allow us to send emails from our Gmail account.
Have a look at the Python program that follows in order to get a better grasp of it: 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:
If we run the program with our email address in place of the receiver’s email address, i.e., Reciever@gmail.com, we will discover that the e-mail is in fact sent to the e-mail address that we entered as the receiver’s email address. This is the same thing that we can see in the output image that is located above.