bfdi533 has asked for the wisdom of the Perl Monks concerning the following question:

I have been looking into Email::Folder to access mbox email files and re-process them.

What I have not been able to find through SuperSearch or through a search of CPAN is a way to sort the contents that the mbox when iterating through the emails. This is important for my re-processing effort to have the email in date order.

I have borrowed code from this post in order to compose the body of my code so far: Re: Gmailize your mbox.

Does anyone know of a way to sort the email using Email::Folder? Or do I need to use a different mbox processing module that has sort capabilities that I have not been able to find?

Replies are listed 'Best First'.
Re: sorting email with email::folder
by kwaping (Priest) on Jul 31, 2006 at 17:23 UTC
    Try this (untested):
    use Email::Folder; use Date::Manip qw(ParseDate Date_Cmp); my $folder = Email::Folder->new("some_file"); # or whatever my @sorted_by_date = sort { Date_Cmp(ParseDate($a->header("Date")), Pa +rseDate($b->header("Date")) } $folder->messages;

    ---
    It's all fine and dandy until someone has to look at the code.
Re: sorting email with email::folder
by madbombX (Hermit) on Jul 31, 2006 at 17:23 UTC
    The best way that I could think to accomplish something like this would be to sort through the first folder and create a hash with the date (or whichever property of the message you wish to sort by) and message id. Then sort the hash and pull each message by id and put it into a new "sorted" folder. I used the CPAN module Mail::Box::Manager.

    For example:

    use Mail::Box::Manager; my $unsorted_folder = "inbox"; my $sorted_folder = "inbox.sort"; my %msghash; my $mgr = Mail::Box::Manager->new; my $unsortfolder = $mgr->open(folder => $unsorted_folder); my $sortfolder = $mgr->open(folder => $sorted_folder); # iterate over the messages & create the hash foreach my $id ($unsortfolder->messages) { my $message = $unsortfolder->message($id); $msghash{$id} = $message->get('Date'); } # compare the dates & add to new folder foreach my $msg (keys %msghash) { @datesorted = <date sorting algorithm> foreach (@datesorted) { $sortedfolder->addMessage($unsortedfolder->message($_)); } } $unsortfolder->close(); $sortedfolder->close();

    The code is untested. I'm sure there is probably a better way to do this. To sort by dates, look into using the CPAN module Date::Manip. Hope the concept helps.