Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri Dec 02 14:14:14 2016
  4.  
  5. @author: Howard
  6. """
  7.  
  8. import email
  9. import getpass, imaplib
  10. import os
  11. import sys
  12. import datetime
  13.  
  14. detach_dir = raw_input('Enter the path of folder: ')
  15. today = datetime.date.today().isoformat().replace('-','')
  16. timeStamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  17. attachName = 'Attachments_' + today
  18.  
  19. if attachName not in os.listdir(detach_dir):
  20. os.chdir(detach_dir)
  21. os.mkdir(attachName)
  22.  
  23. userName = raw_input('Enter your GMail username: ')
  24. passwd = getpass.getpass('Enter your password: ')
  25.  
  26. try:
  27. imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
  28. typ, accountDetails = imapSession.login(userName, passwd)
  29. if typ != 'OK':
  30. print 'Not able to sign in!'
  31. raise
  32.  
  33. imapSession.select('[Gmail]/All Mail')
  34. typ, data = imapSession.search(None, '(UNSEEN)')
  35. if typ != 'OK':
  36. print 'Error searching Inbox.'
  37. raise
  38.  
  39. # Iterating over all emails
  40. for msgId in data[0].split():
  41. typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
  42. if typ != 'OK':
  43. print 'Error fetching mail.'
  44. raise
  45.  
  46. emailBody = messageParts[0][1]
  47. mail = email.message_from_string(emailBody)
  48. for part in mail.walk():
  49. if part.get_content_maintype() == 'multipart':
  50. #print part.as_string()
  51. continue
  52. if part.get('Content-Disposition') is None:
  53. #print part.as_string()
  54. continue
  55. fileName = part.get_filename().split('.')[0] + '_' + timeStamp + '.' +part.get_filename().split('.')[1]
  56.  
  57. if bool(fileName):
  58. filePath = os.path.join(detach_dir, attachName, fileName)
  59. if not os.path.isfile(filePath) :
  60. print fileName
  61. fp = open(filePath, 'wb')
  62. fp.write(part.get_payload(decode=True))
  63. fp.close()
  64. imapSession.close()
  65. imapSession.logout()
  66. except :
  67. print 'Not able to download all attachments.'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement