30 Jul 2022
Library resources | |
---|---|
PyPI | https://pypi.org/project/imap-tools/ |
Github | https://github.com/ikvk/imap_tools |
Documentation | https://openbase.com/python/imap-tools/documentation |
pip3 install imap-tools
bulk function
use as follows:
bulk=False
, eg:
with MailBox(EMAIL_SERVER).login(EMAIL_ACCOUNT, PASSWORD) as mailbox:
for msg in mailbox.fetch(mark_seen=False, reverse=True, bulk=False): # get all emails one by one, from most recent, without changing read status
output:
-------------------------------
Count Total Emails = 17702 emails found
-------------------------------
test.py finished in 13.5 minutes at 14:36:17.
bulk=True
with MailBox(EMAIL_SERVER).login(EMAIL_ACCOUNT, PASSWORD) as mailbox:
for msg in mailbox.fetch(mark_seen=False, reverse=True, bulk=True): # get all emails in bulk, from most recent, without changing read status
output:
-------------------------------
Count Total Emails = 17702
-------------------------------
test.py finished in 0.7 minutes at 14:42:23.
so 20x faster in that case.
Mailbox actions
with MailBox('imap.mail.com').login('test@mail.com', 'pwd', initial_folder='INBOX') as mailbox:
# COPY messages with uid in 23,27 from current folder to folder1
mailbox.copy('23,27', 'folder1')
# MOVE all messages from current folder to INBOX/folder2
mailbox.move(mailbox.uids(), 'INBOX/folder2')
# DELETE messages with 'cat' word in its html from current folder
mailbox.delete([msg.uid for msg in mailbox.fetch() if 'cat' in msg.html])
# FLAG unseen messages in current folder as \Seen, \Flagged and TAG1
flags = (imap_tools.MailMessageFlags.SEEN, imap_tools.MailMessageFlags.FLAGGED, 'TAG1')
mailbox.flag(mailbox.uids(AND(seen=False)), flags, True)
# APPEND: add message to mailbox directly, to INBOX folder with \Seen flag and now date
with open('/tmp/message.eml', 'rb') as f:
msg = imap_tools.MailMessage.from_bytes(f.read()) # *or use bytes instead MailMessage
mailbox.append(msg, 'INBOX', dt=None, flag_set=[imap_tools.MailMessageFlags.SEEN])