Created
May 20, 2018 16:15
-
-
Save voidspace/53092bdb54215add577643580fe763e6 to your computer and use it in GitHub Desktop.
Example of imaplib to batch delete and expunge emails by subject
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from imaplib import IMAP4_SSL | |
HOST = 'mail.XXXX.com' | |
USERNAME = 'XXXX' | |
PASSWORD = 'XXXX' | |
SUBJECT_CHECK = b'[repository/thing]' | |
with IMAP4_SSL(HOST) as m: | |
m.login(USERNAME, PASSWORD) | |
m.select('INBOX') | |
result, ids_raw = m.search(None, 'ALL') | |
assert result == 'OK' | |
ids = ids_raw[0].split(b' ') | |
counter = 0 | |
for m_id in ids: | |
if counter > 100: | |
m.expunge() | |
break | |
subject = m.fetch(m_id, '(BODY[HEADER.FIELDS (SUBJECT)])')[1][0][1] | |
if SUBJECT_CHECK in subject: | |
m.store(m_id, '+FLAGS', r'(\Deleted)') | |
counter += 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment