mid implementation of message iteration
import imap_tools # imap has two state parts: message order in a folder, and message identity
class MBFolder: def __init__(self, host, email, pwd, folder=None): self._folder = folder self.mailbox = imap_tools.MailBox(host).login(email, pwd, initial_folder=folder) self.uid_validity = None self.last_uid = None # set current folder: mailbox.folder.set('foldername') def list(self): return self.mailbox.folder.list(self._folder) def update(self): # check if for uid in self.mailbox.uids(criteria, miss_no_uid=False): # miss_no_uid maybe adds None items for nonmatching for msg in self.mailbox.fetch(criteria, limit=max_count_to_prevent_server_exception, miss_no_uid=False, mark_seen=False, bulk=True): # headers_only=True raw_size = message.size_rfc822 raw_email = bytes(msg.obj) assert raw_size == 0 or len(raw_email) == raw_size # msg.uid # msg.flags def wait_update(self, timeout): responses = self.mailbox.idle.wait(timeout=timeout) if responses: return self.update() def __enter__(self): self.mailbox.__enter__() stat = self.mailbox.folder.status(self._folder) self.uid_validity = stat.get('UIDVALIDITY') self.uid_next = stat.get('UIDNEXT') self.msg_count = stat.get('MESSAGES') def __exit__(self, *params): self.mailbox.__exit__(*params) with MBFolder('host' 'email', 'pwd', 'folder') as mb: mb.update() while True: mb.wait_update(60)