Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to get data from LinkedIn using Python
Next article icon

How to read Emails from Gmail using Gmail API in Python ?

Last Updated : 01 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to read Emails from your Gmail using Gmail API in Python. Gmail API is a RESTful API that allows users to interact with your Gmail account and use its features with a Python script.

So, let’s go ahead and write a simple Python script to read emails.

Requirements

  • Python (2.6 or higher)
  • A Google account with Gmail enabled
  • Beautiful Soup library
  • Google API client and Google OAuth libraries

Installation

Install the required libraries by running these commands:

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

Run this to install Beautiful Soup:

pip install beautifulsoup4

Now, you have to set up your Google Cloud console to interact with the Gmail API. So, follow these steps:

  • Sign in to Google Cloud console and create a New Project or continue with an existing project.

Create a New Project

  • Go to APIs and Services.

Go to APIs and Services

  • Enable Gmail API for the selected project.

Go to Enable APIs and Services

Enable Gmail API

  • Now, configure the Consent screen by clicking on OAuth Consent Screen if it is not already configured.

Configure Consent screen

  • Enter the Application name and save it.

Enter Application name

  • Now go to Credentials.

Go to Credentials

  • Click on Create credentials, and go to OAuth Client ID.

Create an OAuth Client ID

  • Choose application type as Desktop Application.
  • Enter the Application name, and click on the Create button.
  • The Client ID will be created. Download it to your computer and save it as credentials.json

Please keep your Client ID and Client Secrets confidential.

Now, everything is set up, and we are ready to write the code. So, let’s go.

Code

Approach :

The file ‘token.pickle‘ contains the User’s access token, so, first, we will check if it exists or not. If it does not exist or is invalid, our program will open up the browser and ask for access to the User’s Gmail and save it for next time. If it exists, we will check if the token needs to be refreshed and refresh if needed.

Now, we will connect to the Gmail API with the access token. Once connected, we will request a list of messages. This will return a list of IDs of the last 100 emails (default value) for that Gmail account. We can ask for any number of Emails by passing an optional argument ‘maxResults‘.

The output of this request is a dictionary in which the value of the key ‘messages‘ is a list of dictionaries. Each dictionary contains the ID of an Email and the Thread ID.

Now, We will go through all of these dictionaries and request the Email’s content through their IDs.

This again returns a dictionary in which the key ‘payload‘ contains the main content of Email in form of Dictionary.

This dictionary contains ‘headers‘, ‘parts‘, ‘filename‘ etc. So, we can now easily find headers such as sender, subject, etc. from here. The key ‘parts‘ which is a list of dictionaries contains all the parts of the Email’s body such as text, HTML, Attached file details, etc. So, we can get the body of the Email from here. It is generally in the first element of the list.

The body is encoded in Base 64 encoding. So, we have to convert it to a readable format. After decoding it, the obtained text is in ‘lxml‘. So, we will parse it using the BeautifulSoup library and convert it to text format.

At last, we will print the Subject, Sender, and Email.

Python3




# 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('credentials.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').execute()
  
    # We can also pass maxResults to get any number of emails. Like this:
    # result = service.users().messages().list(maxResults=200, userId='me').execute()
    messages = result.get('messages')
  
    # messages is a list of dictionaries where each dictionary contains a message id.
  
    # iterate through all the messages
    for msg in messages:
        # Get the message from its id
        txt = service.users().messages().get(userId='me', id=msg['id']).execute()
  
        # Use try-except to avoid any Errors
        try:
            # Get value of 'payload' from dictionary 'txt'
            payload = txt['payload']
            headers = payload['headers']
  
            # Look for Subject and Sender Email in the headers
            for d in headers:
                if d['name'] == 'Subject':
                    subject = d['value']
                if d['name'] == 'From':
                    sender = d['value']
  
            # The Body of the message is in Encrypted format. So, we have to decode it.
            # Get the data and decode it with base 64 decoder.
            parts = payload.get('parts')[0]
            data = parts['body']['data']
            data = data.replace("-","+").replace("_","/")
            decoded_data = base64.b64decode(data)
  
            # Now, the data obtained is in lxml. So, we will parse 
            # it with BeautifulSoup library
            soup = BeautifulSoup(decoded_data , "lxml")
            body = soup.body()
  
            # Printing the subject, sender's email and message
            print("Subject: ", subject)
            print("From: ", sender)
            print("Message: ", body)
            print('\n')
        except:
            pass
  
  
getEmails()
 
 

Now, run the script with 

python3 email_reader.py    

This will attempt to open a new window in your default browser. If it fails, copy the URL from the console and manually open it in your browser.

Now, Log in to your Google account if you aren’t already logged in. If there are multiple accounts, you will be asked to choose one of them. Then, click on the Allow button.

Your Application asking for Permission

After the authentication has been completed, your browser will display a message: “The authentication flow has been completed. You may close this window”.

The script will start printing the Email data in the console.

You can also extend this and save the emails in separate text or csv files to make a collection of Emails from a particular sender.



Next Article
How to get data from LinkedIn using Python
author
devansh07
Improve
Article Tags :
  • Python
  • python-utility
Practice Tags :
  • python

Similar Reads

  • How to get data from LinkedIn using Python
    Linkedin is a professional tool that helps connect people of certain industries together, and jobseekers with recruiters. Overall, it is the need of an hour. Do you have any such requirement in which need to extract data from various LinkedIn profiles? If yes, then you must definitely check this art
    3 min read
  • Python | Fetch your gmail emails from a particular user
    If you are ever curious to know how we can fetch Gmail e-mails using Python then this article is for you.As we know Python is a multi-utility language which can be used to do a wide range of tasks. Fetching Gmail emails though is a tedious task but with Python, many things can be done if you are wel
    5 min read
  • How to Send Beautiful Emails in Python
    In this article we will send stylized emails using Python we will be using smtplib. The Python smtplib module defines an SMTP client session object which can be used to send mail to any recipient with an SMTP listener. To send emails to any legitimate email address on the internet, "smtplib" produce
    3 min read
  • How to Get Data from API in Python Flask
    In modern web development, APIs (Application Programming Interfaces) play a crucial role in enabling the interaction between different software systems. Flask, a lightweight WSGI web application framework in Python, provides a simple and flexible way to create APIs. In this article, we'll explore ho
    2 min read
  • How to Make API Call Using Python
    APIs (Application Programming Interfaces) are an essential part of modern software development, allowing different applications to communicate and share data. Python provides a popular library i.e. requests library that simplifies the process of calling API in Python. In this article, we will see ho
    3 min read
  • How to send SMS alert using Python and MSG91 API
    In our college days we most often forget our daily classes, right? To keep track of classes every day, we can send a Notification (i.e, ) SMS Alert regards their classes to their mobile phones using Python. We need to use two functionalities: http module and MSG91 API for sending SMS. import http.cl
    3 min read
  • Sending Email using FastAPI Framework in Python
    Before jumping into the topic directly, let's have a small intro about the technologies we are going to use. As the name suggests, we will be using FastAPI, a Python language framework. FastAPI: FastAPI is a python framework to develop REST Apis. It is very easy to build,  high performance, easy to
    3 min read
  • Making SOAP API calls using Python
    SOAP stands for Simple Object Access Protocol, as the name suggests nothing but a protocol for exchanging structured data between nodes. It uses XML instead of JSON. In this article, we are going to see how to make SOAP API calls using Python. If you want to test out what exactly the payload and res
    3 min read
  • Requesting a URL from a local File in Python
    Making requests over the internet is a common operation performed by most automated web applications. Whether a web scraper or a visitor tracker, such operations are performed by any program that makes requests over the internet. In this article, you will learn how to request a URL from a local File
    4 min read
  • Send mail with attachment from your Gmail account using Python
    In last article, we have discussed the basics of sending a mail from a Gmail account without any subject as well as without any attachment. Today, we will learn how to send mail with attachment and subject using Python. Before moving on, it is highly recommended to learn how to send a simple mail us
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences