In this tutorial, you’ll see how to read email from Gmail using Python. 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.
How to Login to Gmail Using Python
You need three things to login to Gmail using Python. You’ll need a mail server, a username and 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 readmail(): # mail reading logic will come here !!
In the above code, we have defined our required variables for reading email from Gmail. We have defined the username and password using which we’ll be reading the email and the smpt server address and port number. Let’s use the imap module to login 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 the whole code inside a try catch block, so that it makes things easy to debug in case something breaks.
Once we have logged into the email account, we can select the inbox label to read the email.
Let’s move forward and search the mails in the inbox. It would return a list of ids for each email in the account.
type, data = mail.search(None, 'ALL') mail_ids = data id_list = mail_ids.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) 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 RFC822 protocol.
typ, data = mail.fetch(i, '(RFC822)' ) # i is the email id
Here is the full code for the Python utility to read emails from Gmail:
import smtplib import time import imaplib import email # ------------------------------------------------- # # Utility to read email from Gmail Using Python # # ------------------------------------------------ def read_email_from_gmail(): try: mail = imaplib.IMAP4_SSL(SMTP_SERVER) mail.login(FROM_EMAIL,FROM_PWD) mail.select('inbox') type, data = mail.search(None, 'ALL') mail_ids = data id_list = mail_ids.split() first_email_id = int(id_list) latest_email_id = int(id_list[-1]) for i in range(latest_email_id,first_email_id, -1): typ, data = mail.fetch(i, '(RFC822)' ) for response_part in data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part) email_subject = msg['subject'] email_from = msg['from'] print 'From : ' + email_from + '\n' print 'Subject : ' + email_subject + '\n' except Exception, e: print str(e)
Wrapping it Up
In this tutorial, we saw how to read email from Gmail using Python. We used the python module imap to implement the email reading task. Have you ever tried to implement mail reading imap module ? Have you ever encountered any issues trying to read email? Do let us know your thoughts in the comments below.