Skip to content
Related Articles

Related Articles

Improve Article
Fetching recently sent mails details sent via a Gmail account using Python
  • Last Updated : 28 Jul, 2020

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.
  • Establsih 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.

# import the modules
import imaplib                              
import email
from email.header import decode_header
import webbrowser
import os
# establish conneection with Gmail
server =""                     
imap = imaplib.IMAP4_SSL(server)
# intantiate the username and the passwprd
username ="" 
password ="********"
# login into the gmail account
imap.login(username, password)               
# select the e-mails
res, messages ='"[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 :


 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :