-
-
Save jasonrdsouza/1674794 to your computer and use it in GitHub Desktop.
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() |
Note 2: This script works on both regular gmail, and google apps accounts.
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)
Hii plz i need the same code for hotmail account can any one help pllz
i had a problem .. and fix it , apply this google account configuration
https://support.google.com/accounts/answer/6010255
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
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
Can you communicate to exchange ideas at the expense of Facebook
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
why would this error show up?
python3 users replace line 19 by
mail = mail.message_from_bytes(email_body)
@alphaguy4 thanks for sharing the alternative
Hello, I am getting Subject and body in encoded format , start of subject is like :=?UTF-
can anyone help me out?
Re less-secure apps: you can also turn on two-factor auth and generate an app-specific password, which is a better option.
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)
I am getting error in the below line
fp = open(att_path, 'wb')
error is as follows :
OSError: [Errno 22] Invalid argument: '.\Google [email protected]_hw1answer'
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
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. :)
@amarmeena1992 you can fork this gist by using Fork button (present on the top right) and can put your modified version there
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
@ashuapple You Have to Enable IMAP Access in your Google Account.
See This Article : https://support.google.com/accounts/answer/6010255
Note: This script requires that the gmail account in question has IMAP enabled.