Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Very basic example of using Python and IMAP to iterate over emails in a gmail folder/label. http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/
#!/usr/bin/env python
#
# Very basic example of using Python and IMAP to iterate over emails in a
# gmail folder/label. This code is released into the public domain.
#
# RKI July 2013
# http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/
#
import sys
import imaplib
import getpass
import email
import email.header
import datetime
EMAIL_ACCOUNT = "notatallawhistleblowerIswear@gmail.com"
EMAIL_FOLDER = "Top Secret/PRISM Documents"
def process_mailbox(M):
"""
Do something with emails messages in the folder.
For the sake of this example, print some headers.
"""
rv, data = M.search(None, "ALL")
if rv != 'OK':
print "No messages found!"
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print "ERROR getting message", num
return
msg = email.message_from_string(data[0][1])
decode = email.header.decode_header(msg['Subject'])[0]
subject = unicode(decode[0])
print 'Message %s: %s' % (num, subject)
print 'Raw Date:', msg['Date']
# Now convert to local date-time
date_tuple = email.utils.parsedate_tz(msg['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(
email.utils.mktime_tz(date_tuple))
print "Local Date:", \
local_date.strftime("%a, %d %b %Y %H:%M:%S")
M = imaplib.IMAP4_SSL('imap.gmail.com')
try:
rv, data = M.login(EMAIL_ACCOUNT, getpass.getpass())
except imaplib.IMAP4.error:
print "LOGIN FAILED!!! "
sys.exit(1)
print rv, data
rv, mailboxes = M.list()
if rv == 'OK':
print "Mailboxes:"
print mailboxes
rv, data = M.select(EMAIL_FOLDER)
if rv == 'OK':
print "Processing mailbox...\n"
process_mailbox(M)
M.close()
else:
print "ERROR: Unable to open mailbox ", rv
M.logout()
#!/usr/bin/env python
#
# Very basic example of using Python 3 and IMAP to iterate over emails in a
# gmail folder/label. This code is released into the public domain.
#
# This script is example code from this blog post:
# http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/
#
# This is an updated version of the original -- modified to work with Python 3.4.
#
import sys
import imaplib
import getpass
import email
import email.header
import datetime
EMAIL_ACCOUNT = "notatallawhistleblowerIswear@gmail.com"
# Use 'INBOX' to read inbox. Note that whatever folder is specified,
# after successfully running this script all emails in that folder
# will be marked as read.
EMAIL_FOLDER = "Top Secret/PRISM Documents"
def process_mailbox(M):
"""
Do something with emails messages in the folder.
For the sake of this example, print some headers.
"""
rv, data = M.search(None, "ALL")
if rv != 'OK':
print("No messages found!")
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print("ERROR getting message", num)
return
msg = email.message_from_bytes(data[0][1])
hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
subject = str(hdr)
print('Message %s: %s' % (num, subject))
print('Raw Date:', msg['Date'])
# Now convert to local date-time
date_tuple = email.utils.parsedate_tz(msg['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(
email.utils.mktime_tz(date_tuple))
print ("Local Date:", \
local_date.strftime("%a, %d %b %Y %H:%M:%S"))
M = imaplib.IMAP4_SSL('imap.gmail.com')
try:
rv, data = M.login(EMAIL_ACCOUNT, getpass.getpass())
except imaplib.IMAP4.error:
print ("LOGIN FAILED!!! ")
sys.exit(1)
print(rv, data)
rv, mailboxes = M.list()
if rv == 'OK':
print("Mailboxes:")
print(mailboxes)
rv, data = M.select(EMAIL_FOLDER)
if rv == 'OK':
print("Processing mailbox...\n")
process_mailbox(M)
M.close()
else:
print("ERROR: Unable to open mailbox ", rv)
M.logout()
@psmlbhor

This comment has been minimized.

Show comment Hide comment
@psmlbhor

psmlbhor Jun 15, 2015

I checked your gmail_imap_example.py program and it has a small mistake in it. On line number 38, the 'h' in the decode = email.header.decode_header(msg['Subject'])[0], should be capital

I checked your gmail_imap_example.py program and it has a small mistake in it. On line number 38, the 'h' in the decode = email.header.decode_header(msg['Subject'])[0], should be capital

@sherarIG

This comment has been minimized.

Show comment Hide comment
@sherarIG

sherarIG Jan 11, 2016

Sorry, in this example, how can I get the body of the email printed?
Regards,

Sorry, in this example, how can I get the body of the email printed?
Regards,

@Schizo

This comment has been minimized.

Show comment Hide comment
@Schizo

Schizo Feb 23, 2016

Is this working as well with 2-way-verification?

Schizo commented Feb 23, 2016

Is this working as well with 2-way-verification?

@aniketanvaria

This comment has been minimized.

Show comment Hide comment
@aniketanvaria

aniketanvaria Feb 23, 2016

For me it's printing "LOGIN FAILED!!" what could be possible reason and how to rectify it..

For me it's printing "LOGIN FAILED!!" what could be possible reason and how to rectify it..

@hollerith

This comment has been minimized.

Show comment Hide comment
@hollerith

hollerith Feb 24, 2016

Doesn't work with two-way verification unless:

https://www.google.com/settings/security/lesssecureapps

Doesn't work with two-way verification unless:

https://www.google.com/settings/security/lesssecureapps

@nachobonilla

This comment has been minimized.

Show comment Hide comment
@nachobonilla

nachobonilla May 1, 2016

I'm trying to adapt the code so that i could print some more data from the e-mails. I´m having trouble understanding what this piece of code does:
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print("ERROR getting message", num)
return

    msg = email.message_from_bytes(data[0][1])
    hdr = email.header.make_header(email.header.decode_header(msg['Subject']))

if you could help me i would appreciate it

I'm trying to adapt the code so that i could print some more data from the e-mails. I´m having trouble understanding what this piece of code does:
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print("ERROR getting message", num)
return

    msg = email.message_from_bytes(data[0][1])
    hdr = email.header.make_header(email.header.decode_header(msg['Subject']))

if you could help me i would appreciate it

@cssidy

This comment has been minimized.

Show comment Hide comment
@cssidy

cssidy Jun 6, 2016

I was getting the login failed message, even without two-way verification, until I enabled access from less secure maps in the Gmail settings. Thank you @hollerith for mentioning this https://www.google.com/settings/security/lesssecureapps

cssidy commented Jun 6, 2016

I was getting the login failed message, even without two-way verification, until I enabled access from less secure maps in the Gmail settings. Thank you @hollerith for mentioning this https://www.google.com/settings/security/lesssecureapps

@mkeresztes

This comment has been minimized.

Show comment Hide comment
@mkeresztes

mkeresztes Jul 18, 2016

For two-way verification the best and recommended solution is to generate an app password https://security.google.com/settings/security/apppasswords.

For two-way verification the best and recommended solution is to generate an app password https://security.google.com/settings/security/apppasswords.

@James-Dias

This comment has been minimized.

Show comment Hide comment
@James-Dias

James-Dias Aug 19, 2016

def process_mailbox (M )

What is the parameter (M ) ? You get what ?

Sorry and discomfort

Thank you!

def process_mailbox (M )

What is the parameter (M ) ? You get what ?

Sorry and discomfort

Thank you!

@jos-h

This comment has been minimized.

Show comment Hide comment
@jos-h

jos-h Apr 27, 2017

James-Dias 'M' here is the IMAP4 Instance which is passed to process_mailbox().

jos-h commented Apr 27, 2017

James-Dias 'M' here is the IMAP4 Instance which is passed to process_mailbox().

@ujjaldey

This comment has been minimized.

Show comment Hide comment
@ujjaldey

ujjaldey Jun 10, 2017

body can be obtained by msg.get_payload()

body can be obtained by msg.get_payload()

@bhathiyalokuketagoda

This comment has been minimized.

Show comment Hide comment
@bhathiyalokuketagoda

bhathiyalokuketagoda Jul 2, 2017

nice code, it helps me to understand a lot about email handling, but is there any way to extract the attachments in the email separately or to save a message in as a file.

nice code, it helps me to understand a lot about email handling, but is there any way to extract the attachments in the email separately or to save a message in as a file.

@one3appstudio

This comment has been minimized.

Show comment Hide comment
@one3appstudio

one3appstudio Jul 15, 2017

I have written Python code that downloads the attachments and also generate an excel fie as log which has the hyperlink to the attachments.
Take a look at my blog

I have written Python code that downloads the attachments and also generate an excel fie as log which has the hyperlink to the attachments.
Take a look at my blog

@mcintst

This comment has been minimized.

Show comment Hide comment
@mcintst

mcintst Jul 29, 2017

thanks for getting me started with imaplib

mcintst commented Jul 29, 2017

thanks for getting me started with imaplib

@Fomchenkov

This comment has been minimized.

Show comment Hide comment
@Fomchenkov

Fomchenkov Jul 29, 2017

Hello! How can I get decoded content?
content = str(email.header.make_header(email.header.decode_header(str(msg.get_payload()[0]))))
It returns encoded string :(

Fomchenkov commented Jul 29, 2017

Hello! How can I get decoded content?
content = str(email.header.make_header(email.header.decode_header(str(msg.get_payload()[0]))))
It returns encoded string :(

@tyarr

This comment has been minimized.

Show comment Hide comment
@tyarr

tyarr Aug 22, 2017

line 71 of gmail_imap_python3.py could easily be changed to use pprint instead of print for easier reading 👍
pprint.pprint(mailboxes)

Remember to import pprint

tyarr commented Aug 22, 2017

line 71 of gmail_imap_python3.py could easily be changed to use pprint instead of print for easier reading 👍
pprint.pprint(mailboxes)

Remember to import pprint

@Gusbenz

This comment has been minimized.

Show comment Hide comment
@Gusbenz

Gusbenz Sep 11, 2017

Thanks so much for this!

Gusbenz commented Sep 11, 2017

Thanks so much for this!

@saitejapsk

This comment has been minimized.

Show comment Hide comment
@saitejapsk

saitejapsk Feb 15, 2018

Thanks a lot bro its worked me bro... now i want to read an attachement file from gmail is above code is similar to that one or not..?

Thanks a lot bro its worked me bro... now i want to read an attachement file from gmail is above code is similar to that one or not..?

@PavanTejaReddy

This comment has been minimized.

Show comment Hide comment
@PavanTejaReddy

PavanTejaReddy May 15, 2018

Thanks for the code. Is there a way to read or download an attachment ? I have been looking for it from 2 days, but didn't find any. Can someone help me plz.
Thank You

Thanks for the code. Is there a way to read or download an attachment ? I have been looking for it from 2 days, but didn't find any. Can someone help me plz.
Thank You

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment