Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python script to access a gmail account and download particular emails
import email, getpass, imaplib, os
detach_dir = '.' # directory where to save attachments (default: current)
user = raw_input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("")
m.login(user,pwd)"cs2043") # here you a can choose a mail box like INBOX instead
# use m.list() to get all the mailboxes
resp, items =, "ALL") # you could filter using the IMAP rules here (check
items = items[0].split() # getting the mails id
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
email_body = data[0][1] # getting the mail content
mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
#Check if any attachments at all
if mail.get_content_maintype() != 'multipart':
print "["+mail["From"]+"] :" + mail["Subject"]
# we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
for part in mail.walk():
# multipart are just containers, so we skip them
if part.get_content_maintype() == 'multipart':
# is this part an attachment ?
if part.get('Content-Disposition') is None:
#filename = part.get_filename()
filename = mail["From"] + "_hw1answer"
att_path = os.path.join(detach_dir, filename)
#Check if its already there
if not os.path.isfile(att_path) :
# finally write the stuff
fp = open(att_path, 'wb')
Copy link

jasonrdsouza commented Jan 25, 2012

Note: This script requires that the gmail account in question has IMAP enabled.

Copy link

jasonrdsouza commented Jan 25, 2012

Note 2: This script works on both regular gmail, and google apps accounts.

Copy link

shresthasagun2 commented Jun 30, 2015

I got the following error while running the file.

Traceback (most recent call last):
File "", line 9, in
File "/usr/lib/python2.7/", line 507, in login
raise self.error(dat[-1])
imaplib.error: [ALERT] Please log in via your web browser: (Failure)

Copy link

b4sphiinx commented Jan 19, 2016

Hii plz i need the same code for hotmail account can any one help pllz

Copy link

miguelcl commented Mar 4, 2016

i had a problem .. and fix it , apply this google account configuration

Copy link

aravindgv commented Apr 17, 2016

This helped me too . We need to enable less secure app access in accounts. Check below link for more info

Copy link

shyamksonata commented Aug 6, 2016

it asked for my user name, I provided user name and pressed enter. Then I entered my password. But nothing appeared after that. No error too. I copied same script from here. Please suggest

Copy link

sidhocine09 commented Sep 9, 2016

Can you communicate to exchange ideas at the expense of Facebook

Copy link

romgrk commented Nov 28, 2016

I had an error while running this, about a 10,000 bytes limit using imaplib. It can be corrected adding this, right after the import:

imaplib._MAXLINE = 100000

Copy link

krisananthu commented Jan 29, 2017

why would this error show up?

Copy link

alphaguy4 commented Feb 2, 2017

python3 users replace line 19 by
mail = mail.message_from_bytes(email_body)

Copy link

hania-batool commented Mar 2, 2017

@alphaguy4 thanks for sharing the alternative

Copy link

Ruchi2291 commented May 8, 2017

Hello, I am getting Subject and body in encoded format , start of subject is like :=?UTF-
can anyone help me out?

Copy link

joemcmahon commented May 17, 2017

Re less-secure apps: you can also turn on two-factor auth and generate an app-specific password, which is a better option.

Copy link

cedb92 commented Jul 23, 2017

Thanks for your code,
For me it works with device password instead of regular user password
About alphaguy4 comment: there's a typo in your comment:

python3 users replace line 19 by
mail = email.message_from_bytes(email_body)

Copy link

PoonamAgrawal12 commented Aug 4, 2017

I am getting error in the below line
fp = open(att_path, 'wb')

error is as follows :
OSError: [Errno 22] Invalid argument: '.\Google'

Copy link

cwlAust commented Dec 4, 2017

Hello Jason,

Thank you for the Python codes, but when I ran it, the program crashed.

I got the following error message:

Traceback (most recent call last):
File "C:\Users\Martin\Desktop\", line 13, in
resp, items =, "ALL") # you could filter using the IMAP rules here (check
File "C:\Python34\lib\", line 660, in search
typ, dat = self._simple_command(name, criteria)
File "C:\Python34\lib\", line 1133, in _simple_command
return self._command_complete(name, self._command(name, args))
File "C:\Python34\lib\", line 881, in _command
', '.join(Commands[name])))
imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

Could you please help. Thank you in advance.


Copy link

amarmeena commented Mar 19, 2018

Thanks for the code. I tweaked it to be more user-friendly and secure. If I want to share my version of the code while giving credits to you under this post, what is the best way to do that? I am a new user of GitHub and this my first github comment, and I don't know the policies to share different versions. :)

Copy link

armujahid commented Apr 7, 2018

@amarmeena1992 you can fork this gist by using Fork button (present on the top right) and can put your modified version there

Copy link

ashuapple commented May 3, 2018

File "/usr/lib/python2.7/", line 507, in login
raise self.error(dat[-1])
imaplib.error: LOGIN failed. Account is blocked. Login to your account via a web browser to verify your identity.
why this error was getting

Copy link

AryaveerSR commented Apr 20, 2020

@ashuapple You Have to Enable IMAP Access in your Google Account.
See This Article :

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