#! /usr/bin/perl
use Net::POP3;
use Date::Manip;
use warnings;
use strict;
# 
# This scripts cleans up a pop3-account by deleting mails older than X days
#
# (c) 2005 Sune Vuorela <pusling@pusling.com>
# Version 0.9
#
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <pusling@pusling.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you
# think this stuff is worth it, you can buy me a beer in return.
#   Sune Vuorela
# ----------------------------------------------------------------------------
#
# Original beerware license is due to Poul-Henning Kamp.

#
#The following four lines should be the only ones needs change to make this work 
#it is your pop3-server, your username and your password(!)
#	Yes - you need to store your password in clear text!
#add :portnumber to $server if your mailserver uses non-standard pop3-port
# $days is number of days that mail should be kept on mailserver.
my $server = 'pop3.server.invalid';
my $user = 'username';
my $pass = 'password';
my $days = 14;





my $err;

my $old_date = DateCalc("today","-$days days",\$err);
print &UnixDate($old_date, "Mails older than %Y-%m-%d %T  will be deleted from server\n");

my $count = 0;
my $left_on_server = 0;

print "Press Enter to Continue or Control-C to stop\n";
my $dummy = <STDIN>;

my $pop = Net::POP3->new($server, Timeout => 60) or die ("Server not found: ".$server."\n");

if ($pop->login($user, $pass))
{
	my $msgnums = $pop->list; # hashref of msgnum => size
		foreach my $msgnum (keys %$msgnums) 
		{
			my $msg = $pop->top($msgnum);
			foreach (@$msg)
			{
				if(/^Date: (.*)$/)
				{
					my $date=ParseDate($1);
					if ($date)
					{
						my $flag = Date_Cmp($date,$old_date);
						if ($flag<0)
						{
							#this could be wrapped in an if() for verbose output
							printf "%-30s%-30s%7s\n","to be deleted:",$date,$msgnum;
							#end wrap
							$pop->delete($msgnum);
							$count++;
						}
						else 
						{
							$left_on_server++;
							#this could be wrapped in a if() for verbose output
							printf "%-30s%-30s%7s\n","left on server:",$date,$msgnum;
							#end wrap
						}
					}
					else 
					{
						#this could be wrapped in a if() for verbose output
						printf "%-30s%-30s%7s\n","bad date, to be deleted:", $1,$msgnum;
						#end wrap
						$pop->delete($msgnum);
						$count++;
					}
					last;
				}
			}
		}
}
else
{#If pop-connect fails
	print "Could not connect to server\n";
	$left_on_server = "Not connected";
}

$pop->quit; #this line actually deletes mail on server. If ^c is pressed before this line is reached, nothing happens!

#some status report
printf "%-30s%20s\n","Mails deleted:",$count;
printf "%-30s%20s\n","Mails left on server:",$left_on_server;

