Advertisement
Guest User

Untitled

a guest
Aug 24th, 2017
642
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.91 KB | None | 0 0
  1. import email
  2. import imaplib
  3. import select
  4. import sys
  5.  
  6. imaplib.Debug = 5
  7.  
  8.  
  9. class MailStore:
  10. def __init__(self, hostname, username, password, callback):
  11. self.connection = imaplib.IMAP4_SSL(hostname)
  12. self.username = username
  13. self.password = password
  14. self.callback = callback
  15. self.running = False
  16.  
  17. def _fetch(self):
  18. try:
  19. typ, data = self.connection.search(None, b'UNSEEN')
  20. except Exception as e:
  21. raise e
  22.  
  23. if typ == 'OK':
  24. mail_ids = data[0]
  25.  
  26. id_list = mail_ids.split()
  27. for i in id_list:
  28. typ, data = self.connection.fetch(i, b'(RFC822)')
  29.  
  30. for response_part in data:
  31. if isinstance(response_part, tuple):
  32. yield email.message_from_bytes(response_part[1])
  33. else:
  34. raise ValueError('Server did accept command: typ=' + typ)
  35.  
  36. def _idle(self):
  37. # noinspection PyProtectedMember
  38. tag = self.connection._new_tag()
  39. self.connection.select(b'inbox')
  40. self.connection.send(tag + b' IDLE\r\n')
  41. response = self.connection.readline()
  42. if response == b'+ idling\r\n':
  43. r, w, e = select.select([self.connection.socket().fileno()],
  44. [],
  45. [],
  46. 60)
  47. if r:
  48. rc, data = self.connection.response(b'FETCH')
  49. if not rc:
  50. raise ValueError(
  51. 'Unexpected reply when idling: rc={}, data={}'.format(
  52. rc,
  53. data),
  54. *sys.exc_info())
  55. self._reply_done()
  56. else:
  57. self._reply_done()
  58.  
  59. else:
  60. raise ValueError("IDLE not handled? : %s" % response)
  61.  
  62. def _run(self):
  63. while self.running:
  64. try:
  65. self.connection.login(self.username, self.password)
  66. self.connection.select(b'inbox')
  67.  
  68. while self.running:
  69. for msg in self._fetch():
  70. self.callback(msg)
  71. self._idle()
  72. finally:
  73. self.connection.close()
  74.  
  75. def _reply_done(self):
  76. self.connection.send(b'DONE\r\n')
  77. rc, data = self.connection.response(b'OK')
  78. if rc != b'OK':
  79. raise ValueError('Error while cancelling idle', *sys.exc_info())
  80.  
  81. def start(self):
  82. self.running = True
  83. self._run()
  84.  
  85. def stop(self):
  86. self.running = False
  87.  
  88. def main():
  89. m = MailStore('imap.gmail.com',
  90. 'test@test.com',
  91. 'hidemeimapassword',
  92. lambda v: print(v))
  93. m.start()
  94.  
  95. if __name__ == '__main__':
  96. try:
  97. main()
  98. except (KeyboardInterrupt, SystemExit) as e:
  99. print('Shutting down application')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement