The Wayback Machine - https://web.archive.org/web/20240824100126/https://www.geeksforgeeks.org/fetching-recently-sent-mails-details-sent-via-a-gmail-account-using-python/
Open In App

Fetching recently sent mails details sent via a Gmail account using Python

Last Updated : 27 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will look at how to fetch a fixed number of recently sent e-mails via a Gmail account using Python. The libraries used in this implementation include imaplib, email. You have to manually go and make IMAP access enabled by going into your Gmail account settings. After this only you could access your Gmail account without logging in the browser. In the setting page, enable this before running the script. Algorithm :

  • Import the imaplib, email, webbrowser and os modules.
  • Establish a imap connection with the Gmail account.
  • Instantiate the username and password variables for the Gmail account.
  • Login into the Gmail account
  • Select the sent mails.
  • Determine the number n of sent e-mails to be retrieved.
  • Iterate the n e-mails and print the sender and the subject of the e-mail.

python3




# import the modules
import imaplib                             
import email
from email.header import decode_header
import webbrowser
import os
 
# establish connection with Gmail
server ="imap.gmail.com"                    
imap = imaplib.IMAP4_SSL(server)
 
# instantiate the username and the password
username ="username@gmail.com"
password ="********"
 
# login into the gmail account
imap.login(username, password)              
 
# select the e-mails
res, messages = imap.select('"[Gmail]/Sent Mail"')  
 
# calculates the total number of sent messages
messages = int(messages[0])
 
# determine the number of e-mails to be fetched
n = 3
 
# iterating over the e-mails
for i in range(messages, messages - n, -1):
    res, msg = imap.fetch(str(i), "(RFC822)")    
    for response in msg:
        if isinstance(response, tuple):
            msg = email.message_from_bytes(response[1])
             
            # getting the sender's mail id
            From = msg["From"]
 
            # getting the subject of the sent mail
            subject = msg["Subject"]
 
            # printing the details
            print("From : ", From)
            print("subject : ", subject)


Output :

                                                                                                                  OUTPUT 



Similar Reads

Python Django | Google authentication and Fetching mails from scratch
Google Authentication and Fetching mails from scratch mean without using any module which has already set up this authentication process. We'll be using Google API python client and oauth2client which is provided by Google. Sometimes, it really hard to implement this Google authentication with these libraries as there was no proper documentation av
12 min read
How to read Emails from Gmail using Gmail API in Python ?
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. RequirementsPython (2.6 or higher)A Google account with Gmail enabl
6 min read
Scrape IMDB movie rating and details using Python and saving the details of top movies to .csv file
We can scrape the IMDb movie ratings and their details with the help of the BeautifulSoup library of Python. Modules Needed: Below is the list of modules required to scrape from IMDB. requests: Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests must be learne
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 using Python and learn the basics working of 'smtpli
4 min read
Handling mails with EZGmail module in Python
EZGmail is a Python module that can be used to send and receive emails through Gmail. It works on top of the official Gmail API. Although EZGmail does not cover everything that can be done with the Gmail API, it makes the common tasks very simple which are a lot more complicated using Google's own API. In this article, we will take a look at how to
4 min read
E-Mails Notification Bot With Python
Email continues to be a widely used communication method, making it an effective platform for receiving updates and staying connected. However, manual email notifications for recurring events or tasks can be inefficient and time-consuming. Python offers a robust toolset to develop automated email notification bots, enabling seamless and efficient c
3 min read
Fetching top news using News API
News API is a simple JSON-based REST API for searching and retrieving news articles from all over the web. Using this, one can fetch the top stories running on a news website or can search top news on a specific topic (or keyword). News can be retrieved based on some criteria. Say the topic (keyword) to be searched is 'Geeksforgeeks' or might be co
5 min read
Fetching text from Wikipedia's Infobox in Python
An infobox is a template used to collect and present a subset of information about its subject. It can be described as a structured document containing a set of attribute-value pairs, and in Wikipedia, it represents a summary of information about the subject of an article.So a Wikipedia infobox is a fixed-format table usually added to the top right
3 min read
Fetching and Displaying Data with HTMX and FastAPI
HTMX allows us to utilize current AJAX methods in HTML directly, while FastAPI is a strong backend framework for quick and efficient API development. This artilce will examine the way of combining HTMX with FastAPI to develop dynamic web applications. Setting Up FastAPIStep1. First we need Python installed on your machine. To check python installed
3 min read
Gmail Login using Python Selenium
Python scripting is one of the most intriguing and fascinating things to do meanwhile learning Python. Automation and controlling the browser is one of them. In this particular article, we will see how to log in to the Gmail account using Python and the power of selenium. Selenium automates and controls browsers and it’s activity. We can code in ou
4 min read
Getting Instagram profile details using Python
Instagram is a photo and video-sharing social networking service owned by Facebook. In this article, we will learn how can we get Instagram profile details using web scraping. Python provides powerful tools for web scraping, we will be using BeautifulSoup here.Modules required and Installation:Requests : Requests allows you to send HTTP/1.1 request
2 min read
Corona Virus Details in India - Using Python PyQt5
In this article, we will see how we can create a PyQt5 application that tells about the details of coronavirus cases i.e total cases, recovered cases and total deaths across India i.e state wise result. Modules required and Installation: PyQt5 : PyQt is a Python binding of the cross-platform GUI toolkit Qt, implemented as a Python plug-in. PyQt is
3 min read
Application to get address details from zip code Using Python
Prerequisite: Tkinter In this article, we are going to write scripts to get address details from a given Zip code or Pincode using tkinter and geopy module in python, Tkinter is the most commonly used GUI module in python to illustrate graphical objects and geopy is a python module to locate the coordinates of addresses, cities, countries, landmark
2 min read
Get Bank details from IFSC Code Using Python
The Indian Financial System Code (IFSC) is an 11-digit alpha-numeric code used to uniquely classify bank branches within the National Electronic Fund Transfer (NEFT) network by the Central Bank. In this article, we are going to write python scripts to get details of the Bank from the given IFSC code. Methods 1: Module Used: ifscapi: The IfscApi Mod
2 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 well versed with its usage. Gmail provides IMAP acces
5 min read
How to insert current_timestamp into Postgres via Python?
For processing timestamps, PostgreSQL supports two data types timestamp and timestamptz. timestamp datatype helps us create a timestamp without timezone, and timestamptz helps us create a timestamp with a timezone. One may store both date and time with the timestamp datatype. It does not, however, include time zone information. It implies that if y
2 min read
Python - Details of CoronaVirus cases in various countries
In this article we will see how to make a script to get the details of corona virus cases i.e total cases, recovered cases and total deaths only by typing the name of the country. Modules required and Installation: Requests : Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs.
3 min read
Python IMDbPY - Retrieving actor from the movie details
In this article we will see how we can retrieve the actors name performed in the movie from the movie information, movie id is the unique id given to each movie by IMDb. We can use search_movie method to search the movies by their name but it gives many movies as they have same names therefore retrieving a movie by its id is a better option. In ord
2 min read
Python IMDbPY - Retrieving role played by actor from the movie details
In this article we will see how we can retrieve the role played by the actor in a given movie from the movie information, movie id is the unique id given to each movie by IMDb. We can use search_movie method to search the movies by their name but it gives many movies as they have same names therefore retrieving a movie by its id is a better option.
2 min read
Python IMDbPY – Getting series details from the series id
In this article we will see how we can get the series details from the IMDb data base, as on the IMDb site, each TV series and also each of a TV series’ episodes is treated as a regular title, just like movie. In order do this we have to do the following -1. With the help of get_movie method get the series details from the code 2. Save this movie o
1 min read
Get Corona cases details - Python PyQt5
In this article we will see how we can create a PyQt5 application which tells about the cases of corona around the world i.e number of confirmed cases, number of cases in which patient has recovered and total deaths due to corona. Modules required and Installation: PyQt5 : PyQt is a Python binding of the cross-platform GUI toolkit Qt, implemented a
3 min read
Decorator to print Function call details in Python
Decorators in Python are the design pattern that allows the users to add new functionalities to an existing object without the need to modify its structure. Decorators are generally called before defining a function the user wants to decorate. Example: # defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the a
3 min read
Fetch Unseen Emails From Gmail Inbox
Python is a widely used high-level, general-purpose, interpreted, multi-utility, dynamic programming language. It can be used to do a wide range of tasks like machine learning, web application development, cross-platform GUI development, and much more. Fetching Gmail is another of a task that could be achieved by Python. You may need to fetch a mai
2 min read
Data Ingestion via Excel: Comparing runtimes
Data ingestion is the process of obtaining and importing the data for the storage in the database. In this article, we explore different data ingestion techniques used to extract the data from the excel file in Python and compare their runtimes. Let's suppose the excel file looks like this - Using xlrd library Using xlrd module, one can retrieve in
2 min read
How to read hive partitioned table via pyspark
Hive is built on Apache Hadoop and employments a high-level association and inquiry dialect called HiveQL (comparative to SQL) to recover large-scale information put away in disseminated capacity frameworks such as the Hadoop Dispersed Record Framework "HDFS". In this article, we will learn how to read a Hive Partitioned Table using Pyspark. Readin
4 min read
Handling File Uploads via CGI
In this article, we will explore how we can handle file uploads via CGI (Common Gateway Interface) script on Windows machines. We will develop a form in which there will be the functionality of uploading the file, when the user uploads the file and submits the form, the data is been passed to the CGI script and the file that is uploaded will get st
6 min read
Validating Bank Account Number Using Regular Expressions
A bank account number is a unique number that is assigned to the account holder after opening their account in any specific bank. In technical terms, we can consider the Bank account number as the Primary Key. A bank account number enables us to do debit, credit, and other transactions. As per RBI Guidelines, Bank Account Number has a unique struct
6 min read
Python PRAW – Getting the time when a redditor created their account
In Reddit, a redditor is the term given to a user. Here we will see how to fetch the exact time when a redditor created their account. We will be using the created_utc attribute of the Redditor class to fetch the Unix time when the redditor created their account. Example 1 : Consider the following redditor : The user name of the redditor is : spez.
2 min read
Python | Create video using multiple images using OpenCV
As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let's see how to create video using multiple images using OpenCV. Install the following libraries: PIL cv2 Also, check the path before running the code otherwise you will be full with errors. How it works ? Using PIL library we are opening
3 min read
Python | Create a stopwatch using clock object in kivy using .kv file
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial - Learn Kivy with Examples. Clock Object: The Clock object allows you to schedule a function call in
6 min read
Practice Tags :
three90RightbarBannerImg