Skip to content

Instantly share code, notes, and snippets.

@Rathgore
Created May 4, 2012 21:00
Show Gist options
  • Save Rathgore/2597705 to your computer and use it in GitHub Desktop.
Save Rathgore/2597705 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