Skip to content

Instantly share code, notes, and snippets.

Embed
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("imap.gmail.com")
m.login(user,pwd)
m.select("cs2043") # here you a can choose a mail box like INBOX instead
# use m.list() to get all the mailboxes
resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
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':
continue
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':
continue
# is this part an attachment ?
if part.get('Content-Disposition') is None:
continue
#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')
fp.write(part.get_payload(decode=True))
fp.close()
@jasonrdsouza
Copy link
Author

jasonrdsouza commented Jan 25, 2012

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

@jasonrdsouza
Copy link
Author

jasonrdsouza commented Jan 25, 2012

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

@shresthasagun2
Copy link

shresthasagun2 commented Jun 30, 2015

I got the following error while running the file.

Traceback (most recent call last):
File "gmail.py", line 9, in
m.login(user,pwd)
File "/usr/lib/python2.7/imaplib.py", line 507, in login
raise self.error(dat[-1])
imaplib.error: [ALERT] Please log in via your web browser: https://support.google.com/mail/accounts/answer/78754 (Failure)

@b4sphiinx
Copy link

b4sphiinx commented Jan 19, 2016

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

@miguelcl
Copy link

miguelcl commented Mar 4, 2016

i had a problem .. and fix it , apply this google account configuration
https://support.google.com/accounts/answer/6010255

@aravindgv
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
https://support.google.com/accounts/answer/6010255

@shyamksonata
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

@sidhocine09
Copy link

sidhocine09 commented Sep 9, 2016

Can you communicate to exchange ideas at the expense of Facebook

@romgrk
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

@krisananthu
Copy link

krisananthu commented Jan 29, 2017

why would this error show up?

@alphaguy4
Copy link

alphaguy4 commented Feb 2, 2017

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

@hania-batool
Copy link

hania-batool commented Mar 2, 2017

@alphaguy4 thanks for sharing the alternative

@Ruchi2291
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?

@joemcmahon
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.

@cedb92
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)

@PoonamAgrawal12
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 no-reply@accounts.google.com_hw1answer'

@cwlAust
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\gmail2.py", line 13, in
resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
File "C:\Python34\lib\imaplib.py", line 660, in search
typ, dat = self._simple_command(name, criteria)
File "C:\Python34\lib\imaplib.py", line 1133, in _simple_command
return self._command_complete(name, self._command(name, args))
File "C:\Python34\lib\imaplib.py", 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.

Sincerely
CwlAust

@amarmeena
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. :)

@armujahid
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

@ashuapple
Copy link

ashuapple commented May 3, 2018

File "/usr/lib/python2.7/imaplib.py", 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

@AryaveerSR
Copy link

AryaveerSR commented Apr 20, 2020

@ashuapple You Have to Enable IMAP Access in your Google Account.
See This Article : https://support.google.com/accounts/answer/6010255

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