Last quarter I graded labs for a course known as
Bioinformatics Computing I. The students mailed me their labs on a daily basis, and I saved the labs and all of the associated e-mails in an mbox file on my home directory. The professor for the course wanted all of the labs so that he could read see where students were confused and improve the course, so I wrote this Perl script in about an hour save all attachments from everyone who sent me a lab into a reasonably-named directory.
#!/usr/bin/perl -w
use strict;
use Mail::MboxParser;
my @folders = glob '*';
@folders = grep /^lab\d+$/, @folders;
foreach ( @folders ) {
&save_bic_messages( $_ );
}
sub save_bic_messages {
my $mail_folder = shift;
# create the mailbox parser
my $mailbox = Mail::MboxParser->new( $mail_folder, decode => 'ALL'
+);
# iterate through the messages, save all attachments in a folder ba
+sed on
# each person's name
for my $msg ($mailbox->get_messages) {
my %header = %{ $msg->header };
my $from = $header{ 'from' };
# do some magic to get a reasonable name from the addresses
my $name;
if ( $from =~ /(.*)\s+\<.*\>/ ) {
$name = $1;
} elsif ( $from =~ /^([A-Z0-9a-z]+)\@/ ) {
$name = $1;
} else {
$name = $from;
}
$name =~ s/\"//g; # remove quotation marks from names
# make sure that the directory for this folder exists
my $save_dir = "bic1_$mail_folder";
if ( ! -d $save_dir ) {
mkdir $save_dir;
}
# create a directory for each of these names
$save_dir = "$save_dir/$name";
if ( ! -d "$save_dir" ) {
mkdir "$save_dir" or warn "Error creating directory $save_dir
+";
}
# save all of the attachments in the directory
$msg->store_all_attachments(path => "$save_dir") ;
}
}