Skip to content

Instantly share code, notes, and snippets.

@hall757
Forked from Rathgore/delete_old_mail.py
Created September 13, 2023 19:26
Show Gist options
  • Save hall757/a9f5db99aea2c2d2882d25add34c87c5 to your computer and use it in GitHub Desktop.
Save hall757/a9f5db99aea2c2d2882d25add34c87c5 to your computer and use it in GitHub Desktop.
Simple script to delete old messages in an IMAP mailbox
MAIL_SERVER = ''
USERNAME = ''
PASSWORD = ''
MAILBOX = 'Spam'
MAX_DAYS = 7 # Deletes messages older than a week
import imaplib
import datetime
today = datetime.date.today()
cutoff_date = today - datetime.timedelta(days=MAX_DAYS)
before_date = cutoff_date.strftime('%d-%b-%Y')
search_args = '(BEFORE "%s")' % before_date
imap = imaplib.IMAP4(MAIL_SERVER)
imap.login(USERNAME, PASSWORD)
imap.select(MAILBOX)
typ, data = imap.search(None, 'ALL', search_args)
for num in data[0].split():
imap.store(num, '+FLAGS', '\\Deleted')
imap.expunge()
imap.close()
imap.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment