2 # A short python script to remove old read mail from a pop3 mailserver.
3 # Dovetails with fetchmail with keep option.
4 # Run it as a cron job...
5 # Version 0.1 by James Stone (stone1@btinternet.com)
6 # please submit bug reports and code optimisations as you see fit!
12 #user editable section
13 mailserver=["mail.server1","mail.server2"] #list of mailservers
14 login=["login1","login2"] #list of logins for corresponding mailserver
15 password=["pass1","pass2"] #list of passwords (note: chmod 700 for this script)
16 days=2 #number of days to keep on server.
17 localuidlcache="/var/mail/.fetchmail-UIDL-cache" #fetchmail's UIDL cache
18 localuidldate="/var/mail/.UIDLDate" #mold remover's UIDL datefile
19 #end of user editable section
21 readfile=open(localuidlcache, 'r')
22 datefile=open(localuidldate, 'a+')
23 tempfile=open("/tmp/uidltmp", 'w+')
24 popuidllist=[] #list of undeleted uidls on all servers
25 totnum=0 #number of undeleted messages on all servers
28 #connect to each mailserver get all the new message UIDLs and delete any
31 for a in range(len(mailserver)):
32 connect=poplib.POP3(mailserver[a])
33 connect.user(login[a])
34 connect.pass_(password[a])
36 number,size=connect.stat()
38 for mesnum in range(number):
41 for uidldate in datefile:
42 uidldatesplit=uidldate.split(' ')
43 if(connectedto==int(uidldatesplit[2])):
44 if (time.time()-float(uidldatesplit[1]))>(86400*days):
46 recheckuidl=connect.uidl(mesnum+1)
47 recheckuidlsplit=recheckuidl.split(' ')
48 if (recheckuidlsplit[2]==uidldatesplit[0]):
49 print('deleting'+recheckuidlsplit[1])
50 print(connect.dele(recheckuidlsplit[1]))
53 except poplib.error_proto:
54 pass #skip over messages that have already been deleted.
55 if not(messagedeleted):
56 popuidllist.append(connect.uidl(mesnum+1)+' '+str(a))
60 #get rid of lines in uidldate file corresponding to the messages that have been
61 #expired (and hopefully been deleted)
64 for uidldate in datefile:
65 uidldatesplit=uidldate.split(' ')
66 if not(time.time()-float(uidldatesplit[1]))>(86400*days):
67 tempfile.write(uidldate)
69 datefile=open(localuidldate,'w+')
74 datefile=open(localuidldate,'a+')
76 #add date to uidl for any messages still on the server which have been read
77 #(check in readfile) and store in local datefile.
79 for mesnum in range(totnum):
80 popuidl=popuidllist[mesnum]
81 popuidlsplit=popuidl.split(' ')
83 for localuidl in readfile:
84 if(localuidl.find(popuidlsplit[2])<>-1):
87 for stored in datefile:
88 if (stored.find(popuidlsplit[2])<>-1):
90 if not(foundindatefile):
91 datefile.write(popuidlsplit[2]+' '+str(time.time())+' '
92 +popuidlsplit[3]+'\n')