#!/usr/bin/perl

# clear-mailbox 0.2
# by Gav Ford
# revford@blueyonder.co.uk
# http://revford.pwp.blueyonder.co.uk
# 2007-09, updated 2008-01
# access a POP3 mailbox and delete the contents
# Uses some code I found in the CPAN examples.


use Term::ANSIColor qw(:constants);

$hostname = $ARGV[0];
$username = $ARGV[1];
$passwd   = $ARGV[2];

if ($ARGV[2] eq undef)
  {print RED, "Error:", RESET, "  Syntax, usage is 'clear-mailbox mailhost username password'\n";exit}

use Net::Telnet ();
$pop = new Net::Telnet (Telnetmode => 0);
$pop->open(Host => $hostname, Port => 110);


# Read connection message.
$line = $pop->getline;
die RED, $line unless $line =~ /^\+OK/;


# Send user name.
$pop->print("user $username");
$line = $pop->getline;
die RED, $line unless $line =~ /^\+OK/;


# Send password.
$pop->print("pass $passwd");
$line = $pop->getline;
die RED, $line unless $line =~ /^\+OK/;

print "Logged into ", YELLOW, $hostname, RESET, " as ", YELLOW, $username, RESET, 
      " OK, clearing mailbox.\n";


# list and count messages.

$pop->print("list");
$listin = $pop->get;

@list = split(/\n/, $listin);

# remove the "+OK scan listing follows" message
shift @list;
# remove the last line "."
pop @list;

$listnumber = (@list);

print "There are $listnumber emails.\n";

# Delete messages.

$count = 0;

while ($count < $listnumber) {
  $count++;

  $pop->print("dele $count");
  $line = $pop->getline;
  chomp ($line);
  print GREEN, $line, RESET, " ][ $count \n";
  };

$pop->print("quit");
$line = $pop->getline;
die RED, $line unless $line =~ /^\+OK/;

print GREEN, "$line", RESET;

exit

