Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to download all gmail attachments.
# 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.'
@imdadhussain
Copy link

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
Any tips would or working code appretiated in advance
thnaks

@footballqq
Copy link

footballqq commented Mar 19, 2017

thank you~

@maulikparekh2
Copy link

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.
Are you the one who tried signing in?
Google will continue to block sign-in attempts from the app you're using because it has known security problems or is out of date. You can continue to use this app by allowing access to less secure apps, but this may leave your account vulnerable.

Copy link

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.

@Jaan4276
Copy link

Jaan4276 commented Apr 25, 2017

Hi All,
Thanks for your answers,it is very helpful and i need at least one example for download attachments form hotmail(any microsoftmail-without configured in my lappy only from servers) and office 365 accounts and it has two step authentication
Thanks again
Regards
Jaaan

@Jaan4276
Copy link

Jaan4276 commented Apr 25, 2017

How to authenticate hotmail and live accounts .Please give me an example.

Thanks

@leifulstrup
Copy link

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.

@Jaan4276
Copy link

Jaan4276 commented May 2, 2017

How to authenticate office365 and microsoft accounts through python

@AlManja
Copy link

AlManja commented May 13, 2017

Anyone got it working for gmx.com? (I don't use google)
If anyone modified it to work it with gmx.com, please share :-)
Just changing form:
imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
to
imapSession = imaplib.IMAP4_SSL('imap.gmx.com')
didn't work

@Omarmaste
Copy link

Omarmaste commented Jun 5, 2017

hi, i have this error
Not able to download all attachments.

change in line 38 UTF-8
change in line 25 'UNSEEN FROM "XXX@gmail.com"'

but continue this error
Not able to download all attachments.

@MeanderingCode
Copy link

MeanderingCode commented Aug 9, 2017

For anyone else who stumbled upon this:

  • If you want a label, change line 24 to read res = imapSession.select('<label_here>')
  • Create an "app specific password" for gmail in your general google account settings
  • Make sure your python is version 2, or be prepared to make changes

@MiroslavMurar
Copy link

MiroslavMurar commented Sep 12, 2017

It does not work, and I dont have idea why.
Even this code is working well
import smtplib

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("Name1", "passwrd")

msg = "HEj"
server.sendmail("Name1", "Name2", msg)
server.quit()

So it should means that gmail is set up well

@vasone
Copy link

vasone commented Jan 13, 2018

Guys can I ask how you can download attachment from specific person?
What code do I add?
Thank you

@UgoRomi
Copy link

UgoRomi commented Feb 14, 2018

I'm using it with python 3.6 and it works fine with just a few adjustments:

  • line 14 change "raw_input" to "input"
  • line 24 change "[Gmail]/All Mail" to "inbox" (or whatever label you want)
  • line 38 change "email.message_from_string" to "email.message_from_bytes"

@GBULLR
Copy link

GBULLR commented Apr 10, 2018

I cannot get this to work.

Ihave done gmail / inbox
string / bytes
etc.

I find the right emails and all of that but still nothing.

get_payload does not seem to do anything.

Suggestions?

Thank you.

@monkeydust
Copy link

monkeydust commented Apr 18, 2018

Anyone got this to work with gmail recently? Keen on something like this

@nandkishorm
Copy link

nandkishorm commented Jul 17, 2018

how to filter by date?

@nafitriaulia
Copy link

nafitriaulia commented Aug 8, 2018

how to change line 38? so it will support UTF-8?

@nafitriaulia
Copy link

nafitriaulia commented Aug 8, 2018

@lewisde how to change line 38? so it will support UTF-8?

@giorgiberia
Copy link

giorgiberia commented Dec 16, 2018

Anyone got this to work with gmail recently? Keen on something like this

Done

@swesko
Copy link

swesko commented May 17, 2019

keep getting raise EOF parsing error on python 3,X

@MadJayhawk
Copy link

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

@kngeno
Copy link

kngeno commented Oct 16, 2019

@Aths23
Copy link

Aths23 commented Apr 6, 2020

Amazing Working Script Thanks To @baali

@x011
Copy link

x011 commented Apr 22, 2020

@Saifriyami
Copy link

Saifriyami commented Jul 14, 2020

Dears
usful code to check old pictures, thanks, however
When I ran the code it printed the email username and did not do anything more.

@nickgreen43
Copy link

nickgreen43 commented Sep 26, 2020

This is awesome! Thank you

@chaohuichen
Copy link

chaohuichen commented Apr 2, 2021

Hi,
Does anyone find this repo working? I think I am stuck with the login that throws me exception

typ, accountDetails = imapSession.login(userName, passed)

can anyone help?

thank you

@kngeno
Copy link

kngeno commented Apr 3, 2021

Hi @chaohuichen,

Have you tried this? https://gist.github.com/kngeno/5337e543eb72174a6ac95e028b3b6456

Also from @x011on flagging particular emails
https://gist.github.com/x011/d6c346debe22f5fec9e4499643ae1050

Hi,
Does anyone find this repo working? I think I am stuck with the login that throws me exception

typ, accountDetails = imapSession.login(userName, passed)

can anyone help?

thank you

@chaohuichen
Copy link

chaohuichen commented Apr 3, 2021

Hi @chaohuichen,

Have you tried this? https://gist.github.com/kngeno/5337e543eb72174a6ac95e028b3b6456

Also from @x011on flagging particular emails
https://gist.github.com/x011/d6c346debe22f5fec9e4499643ae1050

Hi,
Does anyone find this repo working? I think I am stuck with the login that throws me exception
typ, accountDetails = imapSession.login(userName, passed)
can anyone help?
thank you

Thank you @kngeno. the second gist link works!

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