Home

Using Net::IMAP::Simple to move mailboxes around

2009/02/07

In the past I have described using Net::POP3 (combined with tmail from UW-IMAP and a Perl script) to move inboxes from an old (and proprietary) mail server to a new one. However, if your users keep folders like Sent, Drafts and Trash on the mail server, you have to move these also. And this is where Net::IMAP::Simple enters the picture:

#!/usr/bin/perl

use Net::IMAP::Simple;
use Sys::Syslog;

$host = shift or die;
$user = shift or die;
$pass = shift or die;

openlog("imapcat-tmail", 'pid', 'mail') or die;
syslog('info', 'fetching mail for user %s', $user);
closelog();

# When debugging experiment only on myself
## if ($user ne "yiorgos") { exit 0; }

# Folders that we migrate.  CAUTION:  The Trash folder has to be the last in
# line!  That is because $imap->quit expunges the last open folder.  We want 
# this to be Trash and no other.

# For the time being, INBOX is being carried over by pop3cat-tmail.
## push @folder_list, "INBOX";
push @folder_list, "Sent";
push @folder_list, "Drafts";
push @folder_list, "Trash";

$imap = new Net::IMAP::Simple($host) or die;
$imap->login($user, $pass) or die;

while ($folder = shift(@folder_list)) {
        $nm = $imap->select($folder);
        next unless $nm;
        for ($i = 1; $i < = $nm; $i++) {
                $msg = $imap->get($i);
                open T, "| /storage/bin/tmail2 -I $folder $user";
                print T for @{$msg};
                close T;
                $imap->delete($i);
        }
        $imap->expunge_mailbox($folder);
}

$imap->quit;

## print "Bye.\n";
exit 0;

Some notes:

  1. tmail2 is a local version of tmail with a local quota function implemented in tquota.c. It also allows for the -I switch to be used by ordinary users.
  2. This script should be used with caution. When using it to move mailboxes around, keep in mind that all messages will be marked as new when moved.
  3. I must find time to do the same thing forking a version of mailutil that accepts the user password via a command line switch instead of the terminal.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: