python script as an emergency mailbox cleaner

Alex Martelli aleax at aleax.it
Sat Sep 20 16:03:18 CEST 2003


All my mailboxes have been filling up with files of about 130k to 150k, no 
doubt copies of some immensely popular virus.  So, I've no doubt lost lots
of real mail because of "mailbox full" conditions (the proliferating fake 
bounce messages more or less ensure nobody knows their mail to me has 
bounced, either).

As an emergency response I and Anna developed, over the last half hour, a 
small Python script to be run from cron every few minutes and automatically
scrub any POP3 mailbox from files in the target size range.  I'm saving them
to a local file for potential later perusal, but that's obviously easy to 
comment out if needed.  Here's the tiny script in question...:

import poplib
import time

print 'Start at', time.asctime()

host = 'pop.mail.yahoo.com'
port = 110
user = 'aleaxit'
pasw = 'secret'

logfilename = 'bigjunk'
minsize = 130000
maxsize = 180000
fromtag = 'From aleaxit at yahoo.com  %s\n'

ps = poplib.POP3(host, port)
ps.user(user)
ps.pass_(pasw)

messages = ps.list()
print '%d messages, %d bytes' % (len(messages[1]), messages[-1])

logfile = open(logfilename, 'a')

for sms in messages[1]:
    sid, ssize = sms.split()
    if minsize <= int(ssize) < maxsize:
        message = ps.retr(sid)
        print 'retrieving and deleting msg#%s, %d bytes, %d lines' % (
            sid, message[-1], len(message[1]))
        logfile.write(fromtag % time.asctime())
        for line in message[1]:
            logfile.write(line)
            logfile.write("\n")
        logfile.write('\n')
        ps.dele(sid)

ps.quit()

print 'Done at', time.asctime()
print


Hope it can come in useful to somebody...!!!

Alex & Anna





More information about the Python-list mailing list