#!/usr/bin/perl
use strict;
use warnings;
use Mail::IMAPClient;

my $usage = 
"ARGS must be :
\targv1 : mbox file
\targv2 : imap host
\targv3 : imap user (password will be prompted)
\targv4 : destination mailbox on imap server\n";

die($usage) if(@ARGV != 4);
my ($file,$host,$user,$dest) = @ARGV;

my $password = '';
print "Please enter password:\n";
while((my $c = getc) ne "\n"){ $password .= $c; }

my $imap  = new Mail::IMAPClient( 'Server' => $host , 'User' => $user , 'Password' => $password  ) or die "Unable to connect to imap server\n";

foreach my $folder ($imap->folders) {
	open(MBOX,'>',$folder);
	$imap->select($folder) or die "Unable to select folder $@\n";
	print "-- Messages in $folder --\n";
	my @list = $imap->messages or die "$folder: Unable to fetch message list $@";
	foreach my $mess (@list){ 
		my @output = $imap->fetch(($mess,'RFC822')) or die "Unable to fetch$@";
		print MBOX "$output[1]" if(defined($output[1]));
	}
	close(MBOX);
}
$imap->disconnect() or die "Unable to disconnect\n";

