Python-spam

Script I wrote to rotate and delete spam. We send almost all spam from all users to one poor soul named test. I move the spam in this user's inbox into folders by date, and delete the spam once it gets about a month old. Anyone who hasn't figured out they are missing a real mail that might have been classified as spam a month ago, before today, is out of luck.

import datetime, time, cyruslib, sys, smtplib, traceback
from datetime import date
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# script to delete old spam mail from user test
# sends an email to the sysadmin  if completed
# with no errors

f = open('/root/new-rotate.txt','r+')
last_week = f.readline()
#print last_week

# figure out what week it is today
td = date.today()
this_week = str(date.isocalendar(td)[1])

#print this_week

# If the week is the same as in the file, we have already rotated.
if this_week == last_week:
    f.close()
    print "exit, not a new week"
    sys.exit()

# Okay, we want to rotate folders and delete very old spam

# what week was four weeks ago?
four_weeks = td - datetime.timedelta(weeks=4)
del_spam = str(date.isocalendar(four_weeks)[1])
#print(del_spam)

m = cyruslib.CYRUS()
m.login("postmaster", "xxxxxx")
old_mail = 'user.test.archive-%s' % del_spam
#print old_mail
try:
    m.sam(old_mail, "postmaster", "c")
    m.dm(old_mail)
    new_mail = 'user.test.archive-%s' % this_week
#    print new_mail
    m.rename("user.test.archive", new_mail)
    m.cm("user.test.archive")
    m.logout()

    # if it works, print new week to file
    f.seek(0)
    f.write(this_week)
    f.close()
except:
    f.close()
    n = open('/root/rotate-errors.txt','r+')
    traceback.print_exc(file=n)
    n.close()
    msg = MIMEMultipart('alternative')
    me = "root@shadlen.org"
    you = "sysadmin@shadlen.org"
    msg
    msg['Subject'] = 'Mail rotation did not work'
    msg['From'] = me
    msg['To'] = you
    text = 'Bummer, didn\'t work.'
    message = MIMEText(text, 'plain')
    msg.attach(message)
    s = smtplib.SMTP('smtp.shadlen.org')
    s.sendmail(me, you, msg.as_string())
    s.quit()
  LinkedIn