Advertisement
Guest User

Untitled

a guest
Sep 8th, 2017
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.29 KB | None | 0 0
  1. # Links:
  2. #   [1] https://gist.github.com/robulouski/7441883
  3. #   [2] https://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/
  4. #   [3] http://www.faqs.org/rfcs/rfc3501.html
  5. #
  6. # Если возникает ошибка:
  7. #   imaplib.error: b'[ALERT] Please log in via your web browser:
  8. # https://support.google.com/mail/accounts/answer/78754 (Failure)'
  9. #
  10. # То для ее решения выполняем следующие действия:
  11. #   1. On your computer, open Gmail.
  12. #   2. In the top right, click Settings Settings.
  13. #   3. Click Settings.
  14. #   4. Click the Forwarding and POP/IMAP tab.
  15. #   5. In the "IMAP Access" section, select Enable IMAP.
  16. #   6. Click Save Changes.
  17. #
  18. # Потом заходим сюда https://myaccount.google.com/lesssecureapps и
  19. # переключаем ползунок на ON.
  20. #
  21. # Собственно, делаем все то, что написано по ссылке (
  22. # https://support.google.com/mail/accounts/answer/78754).
  23. import email
  24. from imaplib import IMAP4, IMAP4_SSL
  25.  
  26.  
  27. class MailDumper:
  28.  
  29.   def __init__(self, imap_host, imap_user, imap_pass, imap_port=None,
  30.                imap_ssl=False):
  31.     self.imap_host = imap_host
  32.     self.imap_user = imap_user
  33.     self.imap_pass = imap_pass
  34.     self.imap_port = imap_port
  35.     self.imap_ssl = imap_ssl
  36.     self.connect()
  37.     self.login()
  38.  
  39.   def connect(self):
  40.     imap_cls = IMAP4_SSL if self.imap_ssl else IMAP4
  41.     if self.imap_port is not None:
  42.       self.client = imap_cls(self.imap_host, self.imap_port)
  43.     else:
  44.       self.client = imap_cls(self.imap_host)
  45.  
  46.   def login(self):
  47.     self.client.login(self.imap_user, self.imap_pass)
  48.  
  49.   def logout(self):
  50.     self.client.logout()
  51.  
  52.   # ...
  53.  
  54.   def get_folders(self):
  55.     typ, data = self.client.list()
  56.     assert(typ == 'OK')
  57.     return data
  58.  
  59.   # ...
  60.  
  61.   def dump(self, mailbox):
  62.     typ, data = self.client.select(mailbox, True)
  63.     assert(typ == 'OK')
  64.     # 'data' is count of messages in mailbox ('EXISTS' response).
  65.     # Это точно не количество!
  66.     print(data)
  67.     # typ, data = self.client.search(None, 'ALL')
  68.     # assert (typ == 'OK')
  69.     # message_ids = data[0].split()
  70.     # print(message_ids)
  71.     typ, data = self.client.uid('search', None, 'ALL')
  72.     assert(typ == 'OK')
  73.     email_uids = data[0].split()
  74.     # Тут нужно создавать треды и сохранять письма
  75.     for email_uid in email_uids:
  76.       typ, data = self.client.uid('fetch', email_uid, '(RFC822)')
  77.       message = email.message_from_bytes(data[0][1])
  78.       print('Subject:', message['subject'])
  79.       print('From:', message['from'])
  80.       for part in message.walk():
  81.         print(part.get_content_type())
  82.         if part.get_content_maintype() == 'text':
  83.           # print(part.get_content_subtype())
  84.           charset = part.get_content_charset('iso-8859-1')
  85.           data = part.get_payload(decode=True)
  86.           print(data.decode(charset))
  87.         else:
  88.           print('[Skipped]')
  89.       print('-' * 40)
  90.  
  91.  
  92. if __name__ == '__main__':
  93.   # Gmail requires use SSL
  94.   dumper = MailDumper('imap.gmail.com', 'sergey.m@upsafe.com', 'wri15hp0fx',
  95.                       imap_ssl=True)
  96.   print('Existing Folders:', dumper.get_folders())
  97.   dumper.dump('inbox')
  98.   dumper.logout()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement