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 mail from your inbox in your project or website for any reason. In this tutorial, we’ll learn about how to fetch unseen emails from Gmail Inbox/Sent Mails.
To begin, we will be required an app password that is generated by Google Security, since using Password cannot be secure using in some projects or scripts directly.
How to Generate App Password :
- Go to account.google.com with your account.
- In left tabs, choose Security.
- Under Signing into Google, Choose App Password.
- Confirm your identity.
- Choose Custom.
- Choose any name for your Application and Generate the Password.
- That’s your App Password. Copy the password, we’ll be needing that.
You’ll also need to Enable IMAP in the Google Settings.
The Library you’ll use are :
- imaplib
- email
- webbrowser
- os
That’s all for the prerequisite. Let’s see the code now.
Python3
import imaplib
import email
from email.header import decode_header
import webbrowser
import os
username = ""
password = ""
imap = imaplib.IMAP4_SSL( "imap.gmail.com" )
result = imap.login(username, password)
imap.select( '"[Gmail]/All Mail"' ,
readonly = True )
response, messages = imap.search( None ,
'UnSeen' )
messages = messages[ 0 ].split()
latest = int (messages[ - 1 ])
oldest = int (messages[ 0 ])
for i in range (latest, latest - 20 , - 1 ):
res, msg = imap.fetch( str (i), "(RFC822)" )
for response in msg:
if isinstance (response, tuple ):
msg = email.message_from_bytes(response[ 1 ])
print (msg[ "Date" ])
print (msg[ "From" ])
print (msg[ "Subject" ])
for part in msg.walk():
if part.get_content_type() = = "text / plain" :
body = part.get_payload(decode = True )
print (f 'Body: {body.decode("UTF-8")}' , )
|
Output: This code will fetch you the top 20 unseen emails in the inbox.
Last Updated :
14 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...