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 imaplib
import email
from email.header import decode_header
import webbrowser
import os
server = "imap.gmail.com"
imap = imaplib.IMAP4_SSL(server)
username = "username@gmail.com"
password = " * * * * * * * * "
imap.login(username, password)
res, messages = imap.select( '"[Gmail]/Sent Mail"' )
messages = int (messages[ 0 ])
n = 3
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 ])
From = msg["From"]
subject = msg["Subject"]
print ("From : ", From)
print ("subject : ", subject)
|
Output :
OUTPUT

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Dec, 2022
Like Article
Save Article