Fenux.Net - The Life of a Geek
Converting Cryus mail directories to MBOXes, because no one else had done it...
Perl
Posted on 4/5/2005 10:27 pm in Perl

In the process of moving to a new web server, I came across a small problem. On the old server, I'd been using Cryus for IMAP access. On the new server, to simplify things with Webmin/Virtualmin, I'm using IMAP-UW instead. It suits my purposes without overcomplicating matters like Cryus seemed to. The problem is that Cyrus uses a directory of email files and IMAP-UW uses one MBOX file with all the messages. I found several programs to convert from MBOX to Cyrus's format, but nothing to go the other way. After a lot of playing, I finally created something that works. And it works pretty well too.

cyrus2mbox.pl
#!/usr/bin/perl

# cyrus2mbox.pl
##################
# This program converts cyrus style mail directories into mbox files.
#
# Written by Jason Burgess of HolosTek, Inc.
#
# This program is provided under the "I don't really care what you do with it,
# but I'm not going to support it" license.
#
# Usage: cyrus2mbox.pl username
# Note: Be sure to change the $cyruspath variable to fit your system.

use Date::Format;

my $user = shift;

#####
# Change this line to reflect your path to the cryus imap mailbox directory
my $cyruspath = "/var/spool/imap/user/$user/";
my $outfile = "$user";

opendir(DIR, $cyruspath);
my @filelist = readdir(DIR);
closedir(DIR);
open(OUTFILE, "> $outfile");

foreach $infile (@filelist)
{
	my $foundit = true;
	if (($infile =~ /.*?\.$/) && ($infile ne '..') && ($infile ne '.'))
	{
		print "\nChecking $infile...";
		my $from = "";
		# Get From: address from file
		open(INFILE, "<$cyruspath$infile");

		while ()
		{
			chomp;
			s/[\x0D\x0A]//g;
			if (/^From\:\ (.*)$/)
			{
				if ($foundit)
				{
					print $_ . "\t";
					$from = $1;
					$foundit = 0;
				}
			}
		}
		close(INFILE);

		# Get Date from file information.
		my @fileinfo = stat($cyruspath . $infile);
		my $date = time2str("%a %b %e %T %Y", $fileinfo[10]);

		# Write header.
		print OUTFILE sprintf("From %s %s\n", $from, $date);
	
		# Write email to file
		open(INFILE, "<$cyruspath$infile");
		while ()
		{
			s/[\x0D\x0A]//g;
			print OUTFILE "$_\n";
		}
		close(INFILE);

		# Print a blank line between messages
		print OUTFILE "\n";
	}
}

close(OUTFILE);
print "\n\nDone\n";
Creative Commons License  Subscribe with Bloglines  Get Daily Wisdom!
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
© 2000-2012 Jason Burgess