Skip to content

Instantly share code, notes, and snippets.

@alexlafalce
Forked from baali/dlAttachments.py
Last active April 19, 2017 05:38
Show Gist options
  • Save alexlafalce/2b3b07bdf1cebe2db705c04bda267d7a to your computer and use it in GitHub Desktop.
Save alexlafalce/2b3b07bdf1cebe2db705c04bda267d7a to your computer and use it in GitHub Desktop.

Revisions

  1. @baali baali revised this gist May 8, 2012. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions dlAttachments.py
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@
    # 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
  2. @baali baali created this gist May 8, 2012.
    57 changes: 57 additions & 0 deletions dlAttachments.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    # 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.

    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.'