Learn how to read mails in Python

Cloudytechi
4 min readSep 29, 2021

To peruse Emails from an Email Server we utilize the Internet Message Access Protocol IMAP convention. Despite the fact that you can visit the email specialist co-op site like gmail.com and gaze upward the messages present in your Inbox, it is cool to compose a Python script that can peruse or get Emails from your mail Inbox. Also, here in this Python instructional exercise, I will walk you through the means you need to follow to bring messages from your Email Inbox.

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.

When we try to access our Gmail account with any programming language or Third-party package we receive the following error.

imaplib.IMAP4.error: b’[ALERT] Application-specific password required: https://support.google.com/accounts/answer/185833 (Failure)’

You’re getting this error message because Gmail blocks third-party app or package requests if 2-Step Verification is enabled for your account. You can fix this error by simply turning off two-step verification, but I wouldn’t suggest it. Instead, you can use the Gmail app password and generate an alternate app password for your Gmail account. With this, you don’t have to turn off your 2-step verification and you can access your Gmail account using Python or a third-party package.

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

Step 2

Step 3

Step 4

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.

We use this library to connect to the server of the email service provider (in our case Gmail) and log in to the server with the credentials.

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.

#Python program to read emails from Gmail.

#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

Output

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.

You do not need to do it if you are using a different email provider or server there you can log in to your account with the Plain password.

--

--

Cloudytechi

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