In this tutorial, you’ll see how to read an email from Gmail using Python 3. In order to accomplish the mail reading task, we’ll make use of the imaplib Python module. imaplib is a built-in Python module, hence you don’t need to install anything. You simply need to import the module.
Source code from this tutorial can be found at GitHub.
You can also use Gmail API to read Email From Gmail Using Python.
How to Login to Gmail Using Python
You need to enable “less secure apps” from your Google account. Once that is done you need three things to log in to Gmail using Python. You’ll need a mail server, a username, and a password. In this case, since we are trying to login to Gmail, our mail server would be either imap.gmail.com or smtp.gmail.com. If you are trying to read the incoming mail your incoming mail server would be imap.gmail.com and if you are trying to send mail then your outgoing mail server would be smtp.gmail.com. Hence, our mail server is imap.google.com. Username and password are your Gmail username and password. Let’s start by writing some code:
ORG_EMAIL = "@gmail.com"
FROM_EMAIL = "yourEmailAddress" + ORG_EMAIL
FROM_PWD = "yourPassword"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT = 993
def read_email_from_gmail():
# mail reading logic will come here !!
In the above code, we have defined our required variables for reading an email from Gmail. We have defined the username and password using which we’ll be reading the email and the SMTP server address and port number. Let’s use the IMAP module to log in to Gmail using the above credentials.
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(FROM_EMAIL,FROM_PWD)
We just used the IMAP module to connect to the SMTP server over SSL. Using the email address and password defined above we logged into the email account. I would recommend putting the whole code inside a try-catch block so that it makes things easy to debug in case something breaks.
Also read: Creating a Web App Using Angular 4
Once we have logged into the email account, we can select the inbox label to read the email.
mail.select('inbox')
Let’s move forward and search the emails in the inbox. It would return a list of ids for each email in the account.
data = mail.search(None, 'ALL')
mail_ids = data[1]
id_list = mail_ids[0].split()
Using the first email id and last email id, we’ll iterate through the email list and fetch each email’s subject and header.
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])
Read Email From Gmail Using Python
Let’s iterate through the email and fetch the email with a particular Id. We’ll fetch the email using the RFC822 protocol.
data = mail.fetch(str(i), '(RFC822)' ) # i is the email id
Here is the full code for the Python utility to read emails from Gmail:
# Python 3.8.0
import smtplib
import time
import imaplib
import email
import traceback
# -------------------------------------------------
#
# Utility to read email from Gmail Using Python
#
# ------------------------------------------------
ORG_EMAIL = "@gmail.com"
FROM_EMAIL = "your_email" + ORG_EMAIL
FROM_PWD = "your-password"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT = 993
def read_email_from_gmail():
try:
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(FROM_EMAIL,FROM_PWD)
mail.select('inbox')
data = mail.search(None, 'ALL')
mail_ids = data[1]
id_list = mail_ids[0].split()
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])
for i in range(latest_email_id,first_email_id, -1):
data = mail.fetch(str(i), '(RFC822)' )
for response_part in data:
arr = response_part[0]
if isinstance(arr, tuple):
msg = email.message_from_string(str(arr[1],'utf-8'))
email_subject = msg['subject']
email_from = msg['from']
print('From : ' + email_from + '\n')
print('Subject : ' + email_subject + '\n')
except Exception as e:
traceback.print_exc()
print(str(e))
read_email_from_gmail()
Wrapping it Up
In this tutorial, we saw how to read an email from Gmail using Python. We used the python module IMAP to implement the email reading task. Have you ever tried to implement email reading using the IMAP module? Have you ever encountered any issues trying to read email? Do let us know your thoughts in the comments below.
Source code from this tutorial can be found at GitHub.