Advertisement
Guest User

Untitled

a guest
Jun 13th, 2016
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. import email
  2. import getpass, imaplib
  3. import os
  4. import sys
  5.  
  6. detach_dir = '.'
  7. if 'attachments' not in os.listdir(detach_dir):
  8. os.mkdir('attachments')
  9.  
  10. userName = raw_input('Enter username:')
  11. passwd = getpass.getpass('Enter your password: ')
  12.  
  13. try:
  14. imapSession = imaplib.IMAP4_SSL('outlook.office365.com')
  15. typ, accountDetails = imapSession.login(userName, passwd)
  16. if typ != 'OK':
  17. print 'Not able to sign in!'
  18. raise
  19.  
  20. imapSession.select('inbox')
  21. typ, data = imapSession.search(None, 'ALL')
  22. if typ != 'OK':
  23. print 'Error searching Inbox.'
  24. raise
  25.  
  26. # Iterating over all emails
  27. for msgId in data[0].split():
  28. typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
  29. if typ != 'OK':
  30. print 'Error fetching mail.'
  31. raise
  32.  
  33. emailBody = messageParts[0][1]
  34. mail = email.message_from_string(emailBody)
  35. for part in mail.walk():
  36. if part.get_content_maintype() == 'multipart':
  37. # print part.as_string()
  38. continue
  39. if part.get('Content-Disposition') is None:
  40. # print part.as_string()
  41. continue
  42. fileName = part.get_filename()
  43.  
  44. if bool(fileName):
  45. filePath = os.path.join(detach_dir, 'attachments', fileName)
  46. if not os.path.isfile(filePath) :
  47. print fileName
  48. fp = open(filePath, 'wb')
  49. fp.write(part.get_payload(decode=True))
  50.  
  51. fp.close()
  52. imapSession.close()
  53. imapSession.logout()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement