Learn how to read mails in Python

How to Read Emails in Python

For this tutorial, I will be fetching the mails preset in my Gmail inbox, and to be more specific I will be fetching only those emails which are sent from a specific Email address.

This Python tutorial is divided into 3 following sections

This blog on reading emails using python has 2 sections mentioned below:-

  • In Section 1 you will learn how to generate or set up a Gmail App password.
  • In Section 2 we will discuss the libraries we require to write the Python program.
  • In Section 3 we will walk through the Python program to read the Emails.

Set up App Password for Gmail

Step 1

Python imaplib Library

The Python Implib library is a standard Python library for processing IMAP protocols. Since it is part of the standard Python libraries so you don’t have to worry about installing it, it is pre-installed in Python.

How to Read/Fetch emails in Python

Let’s start with importing imaplib, and email modules, and also declare the credentials and host provider server.

#modules
import imaplib
import email

#credentials
username ="codehundred100@gmail.com"

#generated app password
app_password= "aqwertyuiopasdfa"

# https://www.systoolsgroup.com/imap/
gmail_host= 'imap.gmail.com'

#set connection
mail = imaplib.IMAP4_SSL(gmail_host)

#login
mail.login(username, app_password)

#select inbox
mail.select("INBOX")

#select specific mails
_, selected_mails = mail.search(None, '(FROM "noreply@kaggle.com")')

#total number of mails from specific user
print("Total Messages from noreply@kaggle.com:" , len(selected_mails[0].split()))

for num in selected_mails[0].split():
_, data = mail.fetch(num , '(RFC822)')
_, bytes_data = data[0]

#convert the byte data to message
email_message = email.message_from_bytes(bytes_data)
print("\n===========================================")

#access data
print("Subject: ",email_message["subject"])
print("To:", email_message["to"])
print("From: ",email_message["from"])
print("Date: ",email_message["date"])
for part in email_message.walk():
if part.get_content_type()=="text/plain" or part.get_content_type()=="text/html":
message = part.get_payload(decode=True)
print("Message: \n", message.decode())
print("==========================================\n")
break

Conclusion

In this Python tutorial, you learned “How to Read Emails In Python”. In this tutorial, I have read the emails from my Gmail account, and I did not want to stop the 2 step verification that’s why I use the Google App Password to connect my Python script to my Gmail Account.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cloudytechi

Cloudytechi

A tech guy who is more enthusiastic of programming and love coding.