# Something in lines of http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail | |
# Make sure you have IMAP enabled in your gmail settings. | |
# Right now it won't download same file name twice even if their contents are different. | |
import email | |
import getpass, imaplib | |
import os | |
import sys | |
detach_dir = '.' | |
if 'attachments' not in os.listdir(detach_dir): | |
os.mkdir('attachments') | |
userName = raw_input('Enter your GMail username:') | |
passwd = getpass.getpass('Enter your password: ') | |
try: | |
imapSession = imaplib.IMAP4_SSL('imap.gmail.com') | |
typ, accountDetails = imapSession.login(userName, passwd) | |
if typ != 'OK': | |
print 'Not able to sign in!' | |
raise | |
imapSession.select('[Gmail]/All Mail') | |
typ, data = imapSession.search(None, 'ALL') | |
if typ != 'OK': | |
print 'Error searching Inbox.' | |
raise | |
# Iterating over all emails | |
for msgId in data[0].split(): | |
typ, messageParts = imapSession.fetch(msgId, '(RFC822)') | |
if typ != 'OK': | |
print 'Error fetching mail.' | |
raise | |
emailBody = messageParts[0][1] | |
mail = email.message_from_string(emailBody) | |
for part in mail.walk(): | |
if part.get_content_maintype() == 'multipart': | |
# print part.as_string() | |
continue | |
if part.get('Content-Disposition') is None: | |
# print part.as_string() | |
continue | |
fileName = part.get_filename() | |
if bool(fileName): | |
filePath = os.path.join(detach_dir, 'attachments', fileName) | |
if not os.path.isfile(filePath) : | |
print fileName | |
fp = open(filePath, 'wb') | |
fp.write(part.get_payload(decode=True)) | |
fp.close() | |
imapSession.close() | |
imapSession.logout() | |
except : | |
print 'Not able to download all attachments.' |
This comment has been minimized.
This comment has been minimized.
gDesbiens
commented
Aug 24, 2013
It seems that this worked for nincehelser, however it doesn't seems to connect for me. I add 'print 'li 22'' to know it does go, at least to this point, which it does. But I don't get any of the print statement (Not able to sign in!, sign in successful nor Error searching Inbox.), all I got is : Not able to download all attachments.. My gmail account setting is at enable IMAP, if you have any clue why it doesn't work please help, I have made a lot of research without success. I'm working with Python 2.7.3, if it make any difference.. |
This comment has been minimized.
This comment has been minimized.
victorfang
commented
Feb 13, 2014
got the same error as gDesbiens. any fix on this?? |
This comment has been minimized.
This comment has been minimized.
benjamin-l-johnson
commented
Jun 14, 2014
I opened the project in sublime text, converted all the spaces to tabs for indenting then just had to re-indent line 21 but after that it worked perfectly for me |
This comment has been minimized.
This comment has been minimized.
4line
commented
Jul 11, 2014
hi it really help code for me..but is it possible we can download all attachment..say i had download all 5000 of my gmail email.And i after go through i found almost 1000 email got an attachemnt.But I only able to download 40 attachmnt .what is the real problem actually..any idea will definitely appreciate.thanks |
This comment has been minimized.
This comment has been minimized.
BalaSmart
commented
Jul 17, 2014
Hi this s working like a charm to me.. But i want to download specific type of files such as PDF or Xls. Thanks. |
This comment has been minimized.
This comment has been minimized.
BalaSmart
commented
Jul 21, 2014
Is there any way to download attachments from any other email services than gmail? |
This comment has been minimized.
This comment has been minimized.
yeahdef
commented
Apr 21, 2015
@BalaSmart check out python-magic library for resolving filetypes |
This comment has been minimized.
This comment has been minimized.
lbollar
commented
Apr 23, 2015
This is great. Thanks for sharing this. |
This comment has been minimized.
This comment has been minimized.
xiconet
commented
May 17, 2015
Very helpful, thanks again. Now I'm looking for a way to select which attachments I actually want to store as they appear without downloading the file data. I suppose that @BalaSmart: Any provider allowing @anyone: check the "official" python docs for the |
This comment has been minimized.
This comment has been minimized.
sarveshgalgalikar
commented
Jun 11, 2015
What if i just need text portion on the emails and store them into excel or in .csv format? |
This comment has been minimized.
This comment has been minimized.
gpamfilis
commented
Jul 21, 2015
Hello, what if someone wanted to download from a specific label? such as "Work" (created by the user). thank you |
This comment has been minimized.
This comment has been minimized.
lewisde
commented
Aug 6, 2015
I had to update line 38 to support UTF-8 to get it to work. @gpamfilis, change line 24 to the label you want to use. |
This comment has been minimized.
This comment has been minimized.
amit-iiitm
commented
Sep 14, 2015
I am unable to connect to imap.gmail.com the shell shows "gaierror: [Errno -2] Name or service not known" . |
This comment has been minimized.
This comment has been minimized.
Chaya9
commented
Jan 7, 2016
how to extract all the links from email message body using imap in python |
This comment has been minimized.
This comment has been minimized.
pythonpb13
commented
Feb 28, 2016
I want to extract the below parts of the email separately which is in exchange server. To : This field is in UTF-8 characters Ex : उपयोगकर्ता@उदाहरण.कॉम (Hindi, Unicode) From : This field is in UTF-8 characters EX : θσερ@εχαμπλε.ψομ (Ukrainian, Unicode) Subject : This field is in UTF-8 Characters EX : 你好!你好嗎 ? (Chinese, Unicode) Message Body: This field is in UTF-8 characters Ex : Hallo wie geht's dir ? (German, Unicode). The message body in mail is always html format. Name of the attachment file: بلدي مرفق ملف.pdf (It's in Arabic , Unicode). The attachment is in PDF format always. |
This comment has been minimized.
This comment has been minimized.
vshirin1
commented
May 12, 2016
how could i restrict the search to a specific date range / |
This comment has been minimized.
This comment has been minimized.
adityatrilok90
commented
May 30, 2016
I have attachments in my inbox but it is directly going to the "Not able to download all attachments." message.. Could anyone pl help! |
This comment has been minimized.
This comment has been minimized.
ehanove
commented
Jun 13, 2016
I have the same question as vhsirin1, but in terms of only downloading the attachments to only received emails, rather than sent and received. |
This comment has been minimized.
This comment has been minimized.
Heaford
commented
Jun 13, 2016
You also need to make sure that "Access for less secure apps has been turned on" inside of Gmail, this stopped it from working for me until I did this. |
This comment has been minimized.
This comment has been minimized.
sunnyk2057
commented
Sep 6, 2016
how can we add time and subject filter on the code |
This comment has been minimized.
This comment has been minimized.
Kentrg11
commented
Nov 29, 2016
Like many here im looking for a way to search specific dates or last 24 hours |
This comment has been minimized.
This comment has been minimized.
imdadhussain
commented
Mar 8, 2017
i have login through google account using django web app now i want to attach a file from gmail . it is possible |
This comment has been minimized.
This comment has been minimized.
footballqq
commented
Mar 19, 2017
thank you~ |
This comment has been minimized.
This comment has been minimized.
maulikparekh2
commented
Apr 12, 2017
People who are facing "Not able to download all attachments.." error. One of the reason is, Google's security You will get a below mail from Google and Click the allowing access to less secure apps Hyperlink and turn On for less secure apps. |
This comment has been minimized.
This comment has been minimized.
ghost
commented
Apr 24, 2017
People using python 3.+++, you will have to make slight edits to the print option i.e from print 'Not able to sign in!' to print('Not able to sign in!'), raw_input to the input function i.e input('Enter your password'). The rest works like a charm. |
This comment has been minimized.
This comment has been minimized.
Jaan4276
commented
Apr 25, 2017
Hi All, |
This comment has been minimized.
This comment has been minimized.
Jaan4276
commented
Apr 25, 2017
How to authenticate hotmail and live accounts .Please give me an example. Thanks |
This comment has been minimized.
This comment has been minimized.
leifulstrup
commented
May 1, 2017
I am using Python 3.5 and found I needed to use mail = email.message_from_bytes(emailBody) # instead of mail = email.message_from_string(emailBody) to get it working. |
This comment has been minimized.
This comment has been minimized.
Jaan4276
commented
May 2, 2017
How to authenticate office365 and microsoft accounts through python |
This comment has been minimized.
This comment has been minimized.
AlManja
commented
May 13, 2017
•
Anyone got it working for gmx.com? (I don't use google) |
This comment has been minimized.
This comment has been minimized.
Omarmaste
commented
Jun 5, 2017
hi, i have this error change in line 38 UTF-8 but continue this error |
This comment has been minimized.
This comment has been minimized.
MeanderingCode
commented
Aug 9, 2017
For anyone else who stumbled upon this:
|
This comment has been minimized.
This comment has been minimized.
MiroslavMurar
commented
Sep 12, 2017
It does not work, and I dont have idea why. server = smtplib.SMTP('smtp.gmail.com', 587) msg = "HEj" So it should means that gmail is set up well |
This comment has been minimized.
This comment has been minimized.
vasone
commented
Jan 13, 2018
Guys can I ask how you can download attachment from specific person? |
This comment has been minimized.
This comment has been minimized.
UgoRomi
commented
Feb 14, 2018
I'm using it with python 3.6 and it works fine with just a few adjustments:
|
This comment has been minimized.
This comment has been minimized.
GBULLR
commented
Apr 10, 2018
•
I cannot get this to work. Ihave done gmail / inbox I find the right emails and all of that but still nothing. get_payload does not seem to do anything. Suggestions? Thank you. |
This comment has been minimized.
This comment has been minimized.
monkeydust
commented
Apr 18, 2018
Anyone got this to work with gmail recently? Keen on something like this |
This comment has been minimized.
This comment has been minimized.
nandkishorm
commented
Jul 17, 2018
how to filter by date? |
This comment has been minimized.
This comment has been minimized.
nafitriaulia
commented
Aug 8, 2018
how to change line 38? so it will support UTF-8? |
This comment has been minimized.
This comment has been minimized.
nafitriaulia
commented
Aug 8, 2018
@lewisde how to change line 38? so it will support UTF-8? |
This comment has been minimized.
This comment has been minimized.
giorgi1517
commented
Dec 16, 2018
Done |
This comment has been minimized.
This comment has been minimized.
swesko
commented
May 17, 2019
keep getting raise EOF parsing error on python 3,X |
This comment has been minimized.
This comment has been minimized.
MadJayhawk
commented
Aug 12, 2019
Works on Python 3.7 with several changes: Line 38: mail = email.message_from_bytes(emailBody) changed the raises to raise Exception("Not able to sign in!"), raise Exception("Error searching Inbox.") and raise Exception("Error fetching mail.") Line 18: imapSession = imaplib.IMAP4_SSL('imap.gmail.com') changed userName = input('Enter your GMail username:') to userName = "XXXXXX@gmail.com" changed passwd = getpass.getpass('Enter your password: ') to passwd = " "xxxx xxxx xxxx xxxx" (had to get an application specific password for this to work. My Gmail password would not work.) changed detach_dir to .\picture folder/Email Attachments/ to keep the attachments from being saved to current path |
This comment has been minimized.
This comment has been minimized.
kngeno
commented
Oct 16, 2019
A working script thanks to @baali - https://gist.github.com/kngeno/5337e543eb72174a6ac95e028b3b6456 |
This comment has been minimized.
nincehelser commentedJul 20, 2013
This is a really useful script! I ran it on my gmail account and found old pictures that I had lost track of years ago!
Can you point me to more documentation on the imap library functions? Specifically I want to narrow the search based on time. For example, I just want to check the files sent in the last 24 hours.
I'm new to Python and haven't figured out where this sort of stuff is documented yet, so any advice is appreciated.
Thanks!