Guest User

Untitled

a guest
Mar 20th, 2018
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. import imaplib
  2. import email.header
  3. import os
  4. import sys
  5.  
  6. # Your IMAP Settings
  7. host = 'imap.host.com'
  8. user = 'email@adrs.com'
  9. password = 'passwd'
  10.  
  11. # Connect to the server
  12. print('Connecting to ' + host)
  13. mailBox = imaplib.IMAP4_SSL(host)
  14.  
  15. # Login to our account
  16. mailBox.login(user, password)
  17.  
  18. boxList = mailBox.list()
  19. # print(boxList)
  20.  
  21. mailBox.select()
  22. searchQuery = '(SUBJECT "Desired Subject")'
  23.  
  24. result, data = mailBox.uid('search', None, searchQuery)
  25. ids = data[0]
  26. # list of uids
  27. id_list = ids.split()
  28.  
  29. i = len(id_list)
  30. for x in range(i):
  31. latest_email_uid = id_list[x]
  32.  
  33. # fetch the email body (RFC822) for the given ID
  34. result, email_data = mailBox.uid('fetch', latest_email_uid, '(RFC822)')
  35. # I think I am fetching a bit too much here...
  36.  
  37. raw_email = email_data[0][1]
  38.  
  39. # converts byte literal to string removing b''
  40. raw_email_string = raw_email.decode('utf-8')
  41. email_message = email.message_from_string(raw_email_string)
  42.  
  43. # downloading attachments
  44. for part in email_message.walk():
  45. # this part comes from the snipped I don't understand yet...
  46. if part.get_content_maintype() == 'multipart':
  47. continue
  48. if part.get('Content-Disposition') is None:
  49. continue
  50. fileName = part.get_filename()
  51.  
  52. if bool(fileName):
  53. filePath = os.path.join('C:/DownloadPath/', fileName)
  54. if not os.path.isfile(filePath) :
  55. fp = open(filePath, 'wb')
  56. fp.write(part.get_payload(decode=True))
  57. fp.close()
  58.  
  59. subject = str(email_message).split("Subject: ", 1)[1].split("nTo:", 1)[0]
  60. print('Downloaded "{file}" from email titled "{subject}" with UID {uid}.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))
  61.  
  62. mailBox.close()
  63. mailBox.logout()
Add Comment
Please, Sign In to add comment