Mbox to SMTP with Perl

Revision as of 12:54, 24 March 2015 by Jorge de la Cruz (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

    use strict;
    use Email::Folder;
    use Mail::Mailer;
    use MIME::Parser;
    use Net::SMTP;

    my $mbox = $ARGV[0];
    my $email = $ARGV[1];
    my $server = $ARGV[2];

    $server = 'smtp' if(!defined($server));

    die "Usage: $0 mbox dest_address [smtp server]" if(!defined($mbox) || !-f $mbox);
    die "Usage: $0 mbox dest_address [smtp server]" if(!defined($email) || $email !~ m/\@/);

    my $folder = Email::Folder->new($mbox ||
        die "Usage: $0 mbox dest_address [smtp server]
        Forward all mail found in mail file mbox to address.

    my $count=0;
    my @messages=$folder->messages;
    my $total=@messages;

    foreach (@messages){
        my $parser = new MIME::Parser;
        my $entity = $parser->parse_data($_->as_string);
        my $header = $entity->head;
        my $sender = $entity->head->get('From');
        next if $header->get("subject") =~ m/FOLDER INTERNAL/;
        $header->replace('To', $email);
        print "Message $count / $total\n";
        print "Sending message with subject: " . $entity->head->get("subject");
        print " to $email via $server\n";

        my $smtp = new Net::SMTP($server) or die "No mailserver";
        $smtp->mail($sender) or die "unable to set sender";
        $smtp->to($email) or die "unable to address message";
        $smtp->data() or die "unable to start data send";
        $smtp->datasend($entity->as_string()) or die "Message send failed";
        $smtp->dataend() or die "Message end failed";
        print "Done\n\n";
Jump to: navigation, search