SHARE
TWEET

Untitled

a guest Jan 28th, 2016 97 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Email attachments
  2. # Make sure you have IMAP enabled in your gmail settings.
  3. # Right now it won't download same file name twice even if their contents are different.
  4.  
  5. import email
  6. import getpass, imaplib
  7. import os
  8. import sys
  9.  
  10. detach_dir = '.'
  11. if 'attachments' not in os.listdir(detach_dir):
  12.     os.mkdir('attachments')
  13.  
  14. userName = raw_input('Enter your GMail username:')
  15. passwd = getpass.getpass('Enter your password: ')
  16.  
  17. try:
  18.     imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
  19.     typ, accountDetails = imapSession.login(userName, passwd)
  20.     if typ != 'OK':
  21.         print 'Not able to sign in!'
  22.         raise
  23.    
  24.     imapSession.select('[Gmail]/All Mail')
  25.     typ, data = imapSession.search(None, 'ALL')
  26.     if typ != 'OK':
  27.         print 'Error searching Inbox.'
  28.         raise
  29.    
  30.     # Iterating over all emails
  31.     for msgId in data[0].split():
  32.         typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
  33.         if typ != 'OK':
  34.             print 'Error fetching mail.'
  35.             raise
  36.  
  37.         emailBody = messageParts[0][1]
  38.         mail = email.message_from_string(emailBody)
  39.         for part in mail.walk():
  40.             if part.get_content_maintype() == 'multipart':
  41.                 # print part.as_string()
  42.                 continue
  43.             if part.get('Content-Disposition') is None:
  44.                 # print part.as_string()
  45.                 continue
  46.             fileName = part.get_filename()
  47.  
  48.             if bool(fileName):
  49.                 filePath = os.path.join(detach_dir, 'attachments', fileName)
  50.                 if not os.path.isfile(filePath) :
  51.                     print fileName
  52.                     fp = open(filePath, 'wb')
  53.                     fp.write(part.get_payload(decode=True))
  54.                     fp.close()
  55.     imapSession.close()
  56.     imapSession.logout()
  57. except :
  58.     print 'Not able to download all attachments.'
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top