In today’s world, most online services rely on two-factor authentication to secure their users’ accounts. One such method of authentication is the use of One-Time Passwords (OTP) that are sent via email or SMS. In this article, we will learn how to fetch OTP from Gmail using Python.
We will be using the Google API client library for Python to access the Gmail API. Before we dive into the code, make sure you have a Google account and create a new project on the Google Cloud Console. Enable the Gmail API and download the credentials JSON file for the project.
Once you have the credentials, install the following packages using pip:
- google-auth
- google-auth-oauthlib
- google-auth-httplib2
- google-api-python-client
- beautifulsoup4
Let’s now take a look at the code:
# import the required libraries from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import pickle import os.path import base64 import email from bs4 import BeautifulSoup # Define the SCOPES. If modifying it, delete the token.pickle file. SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def getEmails(): # Variable creds will store the user access token. # If no valid token found, we will create one. creds = None # The file token.pickle contains the user access token. # Check if it exists if os.path.exists('token.pickle'): # Read the token from the file and store it in the variable creds with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If credentials are not available or are invalid, ask the user to 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('client_secret.json', SCOPES) creds = flow.run_local_server(port=0) # Save the access token in token.pickle file for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # Connect to the Gmail API service = build('gmail', 'v1', credentials=creds) # Request a list of all the messages result = service.users().messages().list(userId='me', q='from:Upstox <noreply@upstox.com> subject:"OTP to login"').execute() # messages is a list of dictionaries where each dictionary contains a message id. messages = result.get('messages') # If no messages found, return None if not messages: return None # Get the latest message msg = service.users().messages().get(userId='me', id=messages[0]['id']).execute() # Get value of 'payload' from dictionary 'txt' payload = msg['payload'] headers = payload['headers'] # Look for OTP in the body otp = None for part in payload.get('parts', []): body = part.get('body', {}).get('data', '') soup = BeautifulSoup(base64.urlsafe_b64decode(body + '==='), 'html.parser') strong_tag = soup.find('strong', {'style': 'letter-spacing: 24px;'}) if strong_tag: otp = strong_tag.text.strip() break return otp # Call getEmails() function to fetch OTP from Gmail otp = getEmails
This Python script uses Google’s Gmail API to fetch the latest OTP (One-Time Password) received in an email from Upstox. The code imports the necessary libraries and defines the scopes required for accessing the Gmail API.
The getEmails()
function is the core function of the script, which connects to the Gmail API, requests a list of messages matching a specific query, and extracts the latest OTP from the body of the message.
The function first checks for the availability of user access token in a file called token.pickle
. If the file exists, it reads the token and stores it in the creds
variable. If the token is not available or is invalid, it prompts the user to log in to their Gmail account using the InstalledAppFlow
class, which opens a web page for the user to authenticate the script. Once authenticated, the script saves the access token in token.pickle
for future use.
After obtaining the access token, the function builds the Gmail API service object using the build()
method and connects to the user’s Gmail account using the credentials.
The function then sends a request to the Gmail API to retrieve the list of messages that match the query. The query searches for messages that are received from Upstox
with the email address noreply@upstox.com
and have the subject "OTP to login"
.

If no matching messages are found, the function returns None
. Otherwise, it extracts the latest message from the list of messages and gets its payload
and headers
. The function then searches for the OTP in the body of the message by iterating over its parts
. It decodes the body of each part using base64 and uses the BeautifulSoup
library to parse the HTML content. It looks for a strong
tag with a specific style
attribute that contains the OTP value.
Finally, the function returns the OTP value if found, or None
otherwise.
At the end of the script, the getEmails()
function is called, and its return value is stored in the otp
variable.
Overall, the code demonstrates how to use Google’s Gmail API to fetch OTP from an email message automatically. The script can be useful for automating the login process to Upstox, where the OTP is required for authentication.
Discover the world of algo trading with Upstox’s soon-to-be-launched free API. Ready to explore? Open an account with us now using the link below and take the first step towards your trading journey: https://upstox.com/open-account/?f=1TFG
2 Comments
Alex · March 23, 2023 at 3:30 am
Great info …keep going
raghavsmoney · March 23, 2023 at 3:54 am
Thanks Alex 🙂