#!/usr/bin/env python import sys, imaplib, time ##### local configuration # spam folder SPAM = "SPAM" # connect command #connect = lambda : imaplib.IMAP4_stream("/usr/sbin/dovecot --exec-mail imap") connect = lambda : imaplib.IMAP4_stream("/usr/lib/dovecot/imap") ##### end local configuration try: idx = sys.argv.index('--expunge') expunge = True del sys.argv[idx] except ValueError: expunge = False try: idx = sys.argv.index('--seen') seenonly = True del sys.argv[idx] except ValueError: seenonly = False if len(sys.argv) != 2: print "Usage: cleanspam [--expunge] days" print " --expunge: expunge mail after marking older ones deleted" print " --seen: delete only mail marked as seen (read)" print " days: mark mails older than deleted" print " (can be fractional)" sys.exit(2) tnow = time.time() # age in seconds age = float(sys.argv[1]) * 24 * 60 * 60 # IMAP-compatible string for the BEFORE search sentbefore = time.strftime("%d-%b-%Y", time.localtime(tnow - age)) # this is taken from offlineimap/imaputil.py def listjoin(list): start = None end = None retval = [] def getlist(start, end): if start == end: return(str(start)) else: return(str(start) + ":" + str(end)) for item in list: if start == None: # First item. start = item end = item elif item == end + 1: # An addition to the list. end = item else: # Here on: starting a new list. retval.append(getlist(start, end)) start = item end = item if start != None: retval.append(getlist(start, end)) return ",".join(retval) conn = connect() res, num = conn.select(SPAM) if res != 'OK': print "Server error in SELECT" print "full info:", num sys.exit(2) if seenonly: res, uids = conn.search(None, 'BEFORE', sentbefore, 'SEEN') else: res, uids = conn.search(None, 'BEFORE', sentbefore) if res != 'OK': print "Server error in SEARCH" print "full info:", uids sys.exit(2) uids = map(lambda x:int(x), uids[0].split()) if not uids: sys.exit(0) res, info = conn.store(listjoin(uids), "+FLAGS", "(\\Deleted)") if res != 'OK': print "Server error in STORE +FLAGS (\\Deleted)" print "full info:", info sys.exit(2) if expunge: conn.expunge() conn.logout()