Skip to content

Instantly share code, notes, and snippets.

@voidspace
Created May 20, 2018 16:15
Show Gist options
  • Save voidspace/53092bdb54215add577643580fe763e6 to your computer and use it in GitHub Desktop.
Save voidspace/53092bdb54215add577643580fe763e6 to your computer and use it in GitHub Desktop.
Example of imaplib to batch delete and expunge emails by subject
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