Brainstorm's snippets (1/275)

  Delete email spam messages using IMAP

import imaplib
import email
import pprint
import datetime

def delete_spam(imap, date, dry_run):

    spam_subjects = [
        '[SPAM]',
        'Suspect subject',
        # and so on ...
    ]

    dt_from = date.strftime('%d-%b-%Y')
    dt_to =  (date + datetime.timedelta(days=1)).strftime('%d-%b-%Y')
    for spam_subject in spam_subjects:

        # List messages with given subject in specified "date";
        # Matching should already be partial and case insensitive (TODO: check this)
        pattern = 'SUBJECT "%s" SINCE "%s" BEFORE "%s"' % (
            spam_subject,
            dt_from,
            dt_to,
        )

        result, mails_data = imap.search(None, pattern)
        mails_id_list = mails_data[0].split()
        #print(mails_id_list)
        print('deleting %d messages for: %s ...' % (len(mails_id_list), pattern))

        # for i in mails_id_list:
        #     result, mail_data = imap.fetch(i, "(RFC822)")
        #     raw_email = mail_data[0][1].decode()
        #     this_email = email.message_from_string(raw_email)
        #     print(this_email.get('subject'))

        if not dry_run:
            for num in mails_id_list:
               imap.store(num, '+FLAGS', '\\Deleted')
            imap.expunge()


imap_host = 'ssl0.xyz.net'
imap_user = 'info@whatever.it'
imap_pass = '*******************'

imap = imaplib.IMAP4_SSL(imap_host)
imap.login(imap_user, imap_pass)
imap.select('Inbox')

# Elaborate from today and backward for the last 30 days (for example)
first_date = datetime.date.today()
last_date = first_date - datetime.timedelta(days=30)

date = first_date
while True:
    print(date)
    delete_spam(imap, date, dry_run=False)
    date = date - datetime.timedelta(days=1)
    if date < last_date:
        break

imap.close()