Python 3 Gmail API Example to Fetch Recently Sent Emails Using Imaplib Library Full Project For Beginners

Python 3 Gmail API Example to Fetch Recently Sent Emails Using Imaplib Library Full Project For Beginners

 

Welcome folks today in this example we will be fetching recently sent emails in gmail using python and imaplib library. All the full source code of the application is given below.

 

 

Get Started

 

 

In order to get started you need to install the following library using the pip command as shown below

 

pip install imaplib

 

Now you need to enable some settings inside your gmail account to enable imap protocol to fetch recently sent emails

 

Go to Imap Settings

 

 

 

Just grant the imap access inside your gmail account as shown above in the picture

See also  Python 3 PyQt5 Script to Display Virtual OnScreen Keyboard to Take Input Using QT VirtualKeyboard Widget in Canvas Window GUI Desktop App Full Project For Beginners

 

After this make an app.py file and copy paste the following code

 

app.py

 

# import the modules 
import imaplib                           
import email 
from email.header import decode_header 
import webbrowser 
import os 

# establish conneection with Gmail 
server ="imap.gmail.com"                    
imap = imaplib.IMAP4_SSL(server) 

# intantiate the username and the passwprd 
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)

 

See also  Python 3 Tkinter Retail Management System Using MySQL Database GUI Desktop App Full Project For Beginners

 

Here you need to replace the username and password of your gmail account and then run the python script by typing the below command

 

python app.py

 

Now after running this script it will list all your recent sent emails of your gmail account

Leave a Reply