These were sort of hacked together. I'm sure someone could do a better
job. One thing that should be added is the ability to turn the IMAP
message flags into a Status: header of the proper form and back. I
didn't bother. One reason this is slightly non trivial is after
performing an append(), you'd need to then go find out what message
number and/or UID the appended message got. On a live mailbox this has
the possibility of being a race condition if it's not done right.

But this was good enough for us when we were throwing away an old
qpopper machine at my last job.

----- mbox2imap -----
#! /usr/bin/perl -w

use Mail::IMAPClient;

die "Usage: mbox2imap mailbox [file...]" unless @ARGV;

$mbox=shift(@ARGV);

$username = 'root';

print $username." Password: ";
open(TTY, "/dev/tty") or die "Can't read password?!";
system "stty -echo </dev/tty";
chomp($password = <TTY>);
system "stty echo </dev/tty";
close TTY;
print "\n";

$imap = Mail::IMAPClient->new( Server => 'localhost', User => $username,
                                Password => $password,
                                ) or die "Cannot connect to server";

$imap->SETACL($mbox,"root","lrsia") or die("Can't get permission!");

$first=1;

LINE: while(<>) {
  if (/^From /)
  {
    if ($first) {
      $first=0;
      next LINE;
    }
    $imap->append($mbox,$message);
    $message="";
  } else {
    $message .= $_;
  }
}

$imap->append($mbox,$message) if ($message !~ /^$/);

$imap->SETACL($mbox,"root","none") or die("can't remove special permission!");

----- imap2mbox -----
#! /usr/bin/perl -w

use Mail::IMAPClient;
use Time::ParseDate;

$imap = Mail::IMAPClient->new( Server => 'localhost', User => 'root',
                                Password => 'fixme',
                                ) or die "Cannot connect to server";

$mbox = shift(@ARGV);

$imap->SETACL($mbox,"root","lr") or die "Cannot set permission";
$imap->select($mbox) or die "Cannot select folder";

$imap->Peek(1) or die "Cannot peek";

my @msglist = $imap->search("All");

foreach $msg (@msglist) {
  my @envelope=$imap->fetch($msg,"envelope");

  if ($envelope[0] !~ /^\* [0-9]+ FETCH \(UID [0-9]+ ENVELOPE \("(.*)" (NIL|"[^"]*") 
\(\((NIL|"[^"]*") (NIL|"[^"]*") (NIL|"[^"]*") (NIL|"[^"]*")\)\)/ )
     {
      print(STDERR "Bizarre output from fetch: ".$envelope[0]."\n") ;
      $user='"daemon"';
      $dom="NIL";
      $host="NIL";
      $date=localtime(time());
  } else {
    $dom = $4; $user = $5; $host = $6;
    $date = localtime(parsedate($1));
  }

  $dom =~ s/^"(.*)"$/\%$1/ or $dom="";
  $user =~ s/^"(.*)"$/$1/ or $user="";
  $host =~ s/^"(.*)"$/\@$1/ or $host="";

  $msg_txt = $imap->message_string($msg);
  $msg_txt =~ s/[\n]From />From /;

  print "From ",$user,$dom,$host,"  ",$date,"\n",$msg_txt,"\n";
}

$imap->close();
$imap->SETACL($mbox,"root","none") or die "Cannot unset permission";

Reply via email to