Perl Mail Box Manipulation

Brad Marshall <brad.marshall@member.sage-au.org.au>

Introduction

Perl provides a number of interfaces to mailbox folders of which Mail::Box is but one. This article will cover the basic use of it and show how to open a mailbox folder, be it a flat file or over POP or IMAP, and how to manipulate the messages inside.

Modules

First you need to import the required modules - in most cases this will be sufficient:

use Mail::Box::Manager;

Opening Mailboxes

This section will cover how to open mailboxes of 3 different formats - mbox, POP and IMAP.

Mbox Format

To open a mbox folder, simply do the following:

my $mailspool = "/var/spool/mail/username";
my $mgr    = Mail::Box::Manager->new;
my $folder = $mgr->open(folder => $mailspool);

POP3

There are two ways to open a POP folder, as follows:

my $url = 'pop3://user:password@pop.example.com'
my $pop = Mail::Box::POP3->new($url);

my $mgr    = Mail::Box::Manager->new;
my $pop = $mgr->open(type => 'pop3',
            username => 'myname',
            password => 'mypassword',
            server_name => 'pop.example.com');

IMAP4

IMAP folders are opened similarly to POP, as follows:

my $imap   = Mail::Box::IMAP4->new(username => 'myname', 
                     password => 'mypassword',
                     server_name => 'imap.example.com');

my $url    = 'imap4://user:password@imap.example.com');
my $mgr    = Mail::Box::Manager->new;
my $imap   = $mgr->open($url);

Manipulating Folders

To find out the name of the folder you're accessing, simple do the following:

$name = $folder->name;

To check the number of messages in the folder, just:

my $emails = $folder->messages;

To loop over each message simply call the messages subroutine in array context, like so:

foreach $msg ($folder->messages) { # all messages
    # Do something with $msg
}

To extract basic information from a message, such as subject, to, from and the body, simply use the following:

my $subject = $msg->subject;
my @to = $msg->to;
my $from = $msg->sender->address;
my $body = $msg->decoded;

The array returned from the to subroutine consists of Mail::Address objects. To pull the actual address out of it, something like the similar will do:

foreach $to (@to) {
    print "to = ".$to->format."\n";
}

Conclusion

As you can see, Mail::Box provides a very simple interface for pulling out basic information from a mailbox. You can do much more than is shown here, for more information see the perldoc for Mail::Box, Mail::Box-Overview and Mail::Box-Cookbook.