You are on page 1of 10

5/16/2020 How to Read Email From Gmail Using Python - Code Handbook

CODE HANDBOOK 

PYTHON

How to Read Email From Gmail Using Python

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.

You can also use Gmail API to read Email From Gmail Using Python.

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

https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 1/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook

CODE
defHANDBOOK
readmail(): 
# mail reading logic will come here !!

In the above code, we have de ned our required variables for reading email from Gmail. We have de ned 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 de ned 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.

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 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[0]
id_list = mail_ids.split()

Using the rst 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 RFC822 protocol.

https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 2/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook

CODE HANDBOOK
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[0]

id_list = mail_ids.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):


typ, data = mail.fetch(i, '(RFC822)' )

for response_part in data:


if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
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.

https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 3/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook

CODE HANDBOOK jay 


I’m a software developer. I blog about web development related tutorials and articles in my free
time.
See author's posts

 

Related

How To Send Email Using Gmail In Python


November 27, 2018
IN "PYTHON"

How To Read Email From GMAIL API Using Python


November 30, 2018
IN "PYTHON"

Python Web Application Development Using Flask MySQL


July 16, 2015
IN "FLASK"

JANUARY 22, 2017

JAY

# EMAIL, # GMAIL, # PYTHON

SHARE THIS:
Tweet Share 1

ALSO ON CODE HANDBOOK

a year ago • 13 comments 2 years ago • 2 comments 2 years ag


How To Read Understanding How T
Email From JavaScript JavaS
GMAIL API … Promise Prom

41 Comments Code Handbook 🔒  Ava

 Recommend 2 t Tweet f Share Sort by Best

Join the discussion…

Stephan Code • a year ago • edited


This what I get:

[Errno 8] nodename nor servname provided, or not known


None

Process finished with exit code 0

***************

- I have enable "less secure apps" & IMAP in gmail,

- I have modified the code for Python 3, as it says in the


comments.
https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 4/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook

- I have respected the indentation, eventho it doesn't show here:


CODE HANDBOOK 

import smtplib #Also this is GREY


import time # This is also GREY
import imaplib
import email

def read_email_from_gmail():

try:
mail = imaplib.IMAP4_SSL('imap.google.com')
mail.login('myemail', 'mypassword!')
mail.select('inbox')

type, data = mail.search(None, 'ALL')


mail_ids = data[0]

id_list = mail_ids.split()

for i in reversed(id_list):
typ, data = mail.fetch(str.encode(str(i)), '(RFC822)')

for response_part in data:


if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1].decode('utf-
8'))
email_subject = msg['subject']
email_from = msg['from']
print('From : ' + email_from + '\n')
print('Subject : ' + email_subject + '\n')

except Exception as e:
print(str(e))
print(read_email_from_gmail())

6△ ▽ 1 • Reply • Share ›

remi Ehounou > Stephan Code • 5 months ago


You probably solved this already but i am just posting
the solution i used just in case! I just had to go in my
google account and make sure "less secure apps" as well
as imap are enabled in gmail and I verified that I was the
one trying to connect after i try to the first time
△ ▽ • Reply • Share ›

Keegan K • 3 years ago


How can you make it only show the latest email?
2△ ▽ • Reply • Share ›

Etheo > Keegan K • 2 years ago • edited


instead of iterating from last to first ID, just do a single
mail.fetch(latest_email_id, '(RFC822)' )
if that doesn't work (like I tried in Python 3.6.3) you
might need to encode the id to byte (as the fetch is
looking for byte type):
mail.fetch(str.encode(str(latest_email_id)), '(RFC822)' )
or
mail fetch(bytes(str(latest email id) 'utf-8' )
https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 5/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook
mail.fetch(bytes(str(latest_email_id), utf-8 ),
'(RFC822)' )
CODE HANDBOOK 
That, or simply don't convert the latest_email_id to int,
which is much cleaner.
△ ▽ • Reply • Share ›

Matt Pryse • 10 months ago


The range loop was not working when I had only one message
(start=1, stop=1, step=-1). I reversed the ids and iterate through
them with a for loop instead:
mail_ids = data[0].split()
for i in mail_ids[::-1]:
1△ ▽ • Reply • Share ›

Ryan McGrath • 2 years ago • edited


type, data = mail.search(None, 'ALL')

This line breaks the type() function. This should be revised to


something like

response, data = mail.search(None, 'ALL')

Also setting a SMTP_PORT variable that is never used.


1△ ▽ • Reply • Share ›

Mehdi Zarrouk Che • 2 years ago


no data received and no connection done
1△ ▽ • Reply • Share ›

Victor • 4 months ago


Hello ,
I'm french and i've got a problem with this program.
When I save a subject with emphasis, he's sending it back to me
without emphasis.
I'm coding with utf8 so I think it's the RFC822 protocol who
don't accept the emphasis.
If anyone would like to help me thank you so much.
I'm sorry for my english
△ ▽ • Reply • Share ›

Suvarna Sivadas • 9 months ago


i get this error

Traceback (most recent call last):


File "t.py", line 11, in <module>
mail = imaplib.IMAP4_SSL('imap.google.com',993)
File "/usr/lib/python3.6/imaplib.py", line 1283, in __init__
IMAP4.__init__(self, host, port)
File "/usr/lib/python3.6/imaplib.py", line 197, in __init__
self.open(host, port)
File "/usr/lib/python3.6/imaplib.py", line 1296, in open
IMAP4.open(self, host, port)
File "/usr/lib/python3.6/imaplib.py", line 294, in open
self.sock = self._create_socket()
File "/usr/lib/python3.6/imaplib.py", line 1286, in
_create_socket
sock = IMAP4._create_socket(self)
File "/usr/lib/python3.6/imaplib.py", line 284, in
_create_socket
return socket.create_connection((self.host, self.port))
File "/usr/lib/python3.6/socket.py", line 704, in
create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto,
flags):
socket.gaierror: [Errno -2] Name or service not known
△ ▽ • Reply • Share ›

megha shree • a year ago

https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 6/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook

Below is my code in python 2.7 and it's running without giving


CODE HANDBOOK
me any error but not getting any data. 

import email
import imaplib2

EMAIL_USER = 'mailid@gmail.com'
EMAIL_PASSWORD = 'password'
EMAIL_SERVER = 'ns21.interactivedns.com'

def read_mail_from_server():
try:
mail = imaplib2.IMAP4_SSL(EMAIL_SERVER, 993)
mail.login(EMAIL_USER, EMAIL_PASSWORD)
# code, mailboxen = mail.list()
# print(mailboxen)
mail.select('INBOX')

typ, raw_data = mail.search(None, 'ALL')


see more

△ ▽ • Reply • Share ›

Sayyed • a year ago


I am not getting the error ,program run successfully but not
getting the Data
△ ▽ • Reply • Share ›

Tom • a year ago • edited


Hey all - I seem to have successfully accessed the gmail servers
(no more password errors) but now my code throws the
exception every time, even though I'm certainly searching for
existing email subject lines. Here's my code right now. Any
advice would be great!

ORG_EMAIL = "@gmail.com"
FROM_EMAIL = "yourEmailAddress" + ORG_EMAIL
FROM_PWD = "yourPassword"
SMTP_SERVER = "imap.gmail.com"

import smtplib
import time
import imaplib
import email

def read_email_from_gmail():
try:
mail = imaplib IMAP4 SSL(SMTP SERVER)
see more

△ ▽ • Reply • Share ›

Abhijit Phadke • a year ago


I am getting authentication error
△ ▽ • Reply • Share ›

NEHA VARSHNEY > Abhijit Phadke • a year ago


Hey, I am getting the same error. Please share the
insights if you were able to solve it.
Thank You
△ ▽ • Reply • Share ›

Roddd2000 > NEHA VARSHNEY • a year ago


You have to enable "less secure app" to bypass
this. https://myaccount.google.co...
△ ▽ • Reply • Share ›

Sean Brown • 2 years ago


If you use msg['subject'] to get the subject line what would you
do to get the body of the email?
△ ▽ • Reply • Share ›

https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 7/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook

Dominus Labs > Sean Brown • a year ago


CODE HANDBOOK 
Think it is ''c = msg.get_payload()'' but I am not sure.
Haven't tested this yet
△ ▽ • Reply • Share ›

Bharath > Dominus Labs • a year ago


can u please tell in detail .
If Im trying to print c ..its telling that a message
instance is being created
△ ▽ • Reply • Share ›

Neeraj Joon • 2 years ago


how to make it read one newest email from a single email adrr +
i wanted to print the body msg of that latest email
△ ▽ • Reply • Share ›

newswat • 2 years ago • edited


am getting this error:

Traceback (most recent call last):


File "em.py", line 2, in <module>
import smtplib
File "/usr/lib/python2.7/smtplib.py", line 46, in <module>
import email.utils
File "/home/dira/dira/email.py", line 5, in <module>
mail= imaplib.IMAP4_SSL('imap.gamil.com',993)
File "/usr/lib/python2.7/imaplib.py", line 1168, in __init__
IMAP4.__init__(self, host, port)
File "/usr/lib/python2.7/imaplib.py", line 173, in __init__
self.open(host, port)
File "/usr/lib/python2.7/imaplib.py", line 1179, in open
self.sock = socket.create_connection((host, port))
File "/usr/lib/python2.7/socket.py", line 557, in
create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
△ ▽ • Reply • Share ›

Thai Laoquoc > newswat • 2 years ago


'imap.gmail.com' not that line you write down in your
code
△ ▽ • Reply • Share ›

appukuttan mamachan • 2 years ago


Thanks for the tutorial. It was helpful. But on python3, it shows
up errors. Below is an example working code with tweaks. Note
that it will only print the subject.

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[0]

id_list = mail_ids.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):


typ, data = mail.fetch(str(i), '(RFC822)' )
see more

△ ▽ • Reply • Share ›

test app • 2 years ago


no output. just blank
△ ▽ • Reply • Share ›
https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 8/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook
py

CODE HANDBOOK
artemis > test app • 2 years ago 
It's just a function, it's not called. Try adding the line 'def
read_email_from_gmail()' to the end.
△ ▽ • Reply • Share ›

Abhinav Anand • 3 years ago


Does it work with python3
△ ▽ • Reply • Share ›

Etheo > Abhinav Anand • 2 years ago • edited


Not directly. Some modification is required. Here's how
I got it working:

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[0]

id_list = mail_ids.split()

for i in reversed(id_list):
typ, data = mail.fetch(i, '(RFC822)' )

for response_part in data:


if isinstance(response_part, tuple):

see more

1△ ▽ • Reply • Share ›

disqus_s1OiharEwN > Etheo • 2 years ago


thanks !! makes sense
△ ▽ • Reply • Share ›

Evan Mead > Etheo • 2 years ago


Ive typed the corrected code but i get a blank
shell, do i need to send a brand new email for this
to work?
△ ▽ • Reply • Share ›

Abhinav Anand > Etheo • 2 years ago


Thanx
△ ▽ • Reply • Share ›

Sanjay Sharma > Abhinav Anand


• 2 years ago
The code extracts emails but it doesn't
pull all emails for the seacrh condition.
Example: maibox has 1300 emails by
same sender but it only pulls 676. any
suggestions ?
△ ▽ • Reply • Share ›

Dk • 3 years ago • edited


I have implemented this code and get a google warning:

mail.login(FROM_EMAIL,FROM_PWD)
File "C:\...\imaplib.py", line 582, in login
raise self.error(dat[-1])
imaplib.error: b'[ALERT] Please log in via your web browser:
https://support.google.com/... (Failure)'

i.e. Google wants me to use an app that has enhanced security--


not python code.

Other discussions group say to "Go to the "Less secure apps"


section in My Account." on gmail and enable less secure apps.
https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 9/10
5/16/2020 How to Read Email From Gmail Using Python - Code Handbook
Did that, and still getting the above message.
CODE HANDBOOK 
Do you know any work arounds or code changes we can make to
your code above?
△ ▽ • Reply • Share ›

Amit Nirala > Dk • 3 years ago


The cause of this error is the Google Account Security
that is, Google provides security options to secure your
account from unidentified third party applications or
less secure applications, and this security option is
enabled by default.
To resolve this error, just log into your google account,
and visit this link https://myaccount.google.co... , or you
can also manually navigate to this link as
gmail account > click on Profile Image (at top right
corner) > My Account > click on Connected apps & sites
link.

now scroll down to "Connected Apps & Sites" section


and enable "Allow less secure apps" option.
That's it.
△ ▽ 1 • Reply • Share ›

Digamma F > Dk • 3 years ago


In addition, you have to active IMAP and POP services.
(How you do that : https://support.google.com/...
△ ▽ 1 • Reply • Share ›

Ferdinando > Digamma F • 3 years ago


I tried both of these and it didn't work, I still have
this exact same problem. Any idea why? Am
connecting from the UK don't know if it makes

PREVIOUS

Understanding Regular expressions in Python

NEXT

Python Flask Web Application On GE Predix

Proudly powered by WordPress  Theme: Gazette by Automattic.

https://codehandbook.org/how-to-read-email-from-gmail-using-python/ 10/10

You might also like