Advertisement
Guest User

Untitled

a guest
Apr 10th, 2017
653
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. import email
  2. import imaplib
  3. import os
  4.  
  5. SERVER = 'imap.gmail.com'
  6. USERNAME = 'EMAIL ADDRESS'
  7. PASSWORD = 'PASSWORD'
  8.  
  9. class FetchEmail():
  10.  
  11. connection = None
  12. error = None
  13.  
  14. def __init__(self, mail_server, username, password):
  15. self.connection = imaplib.IMAP4_SSL(mail_server)
  16. self.connection.login(username, password)
  17. self.connection.select(readonly=False) # so we can mark mails as read
  18.  
  19. def close_connection(self):
  20. """
  21. Close the connection to the IMAP server
  22. """
  23. self.connection.close()
  24.  
  25. def save_attachment(self, msg, download_folder="/tmp"):
  26. """
  27. Given a message, save its attachments to the specified
  28. download folder (default is /tmp)
  29.  
  30. return: file path to attachment
  31. """
  32. att_path = "No attachment found."
  33. for part in msg.walk():
  34. if part.get_content_maintype() == 'multipart':
  35. continue
  36. if part.get('Content-Disposition') is None:
  37. continue
  38.  
  39. filename = part.get_filename()
  40. att_path = os.path.join(download_folder, filename)
  41.  
  42. if not os.path.isfile(att_path):
  43. fp = open(att_path, 'wb')
  44. fp.write(part.get_payload(decode=True))
  45. fp.close()
  46. return att_path
  47.  
  48. def fetch_unread_messages(self):
  49. """
  50. Retrieve unread messages
  51. """
  52. emails = []
  53. (result, messages) = self.connection.search(None, 'UnSeen')
  54. if result == "OK":
  55. for message in messages[0].decode('utf-8').split(' '):
  56. try:
  57. ret, data = self.connection.fetch(message,'(RFC822)')
  58. except:
  59. print("No new emails to read.")
  60. self.close_connection()
  61. exit()
  62.  
  63. msg = email.message_from_string(data[0][1].decode('utf-8'))
  64. if isinstance(msg, str) == False:
  65. emails.append(msg)
  66. response, data = self.connection.store(message, '+FLAGS','\\Seen')
  67.  
  68. return emails
  69.  
  70. self.error = "Failed to retreive emails."
  71. return emails
  72.  
  73. def parse_email_address(self, email_address):
  74. """
  75. Helper function to parse out the email address from the message
  76.  
  77. return: tuple (name, address). Eg. ('John Doe', 'jdoe@example.com')
  78. """
  79. return email.utils.parseaddr(email_address)
  80.  
  81.  
  82. if __name__ == '__main__':
  83. f = FetchEmail(
  84. mail_server=SERVER,
  85. username=USERNAME,
  86. password=PASSWORD
  87. )
  88. msgs = f.fetch_unread_messages()
  89. for m in msgs:
  90. file_location = f.save_attachment(
  91. msg=m,
  92. download_folder='C:\\tmp'
  93. )
  94. print(file_location)
  95. f.close_connection()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement