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

So, what I need to do is process mail in mbox format:

1) Get a message
2) Do stuff to the body
3) Print the mail back, preserving attachments

I've tried this:
#!/usr/bin/perl use Mail::Mbox::MessageParser; use Email::MIME; use Encode; my $infile = shift @ARGV; Mail::Mbox::MessageParser::SETUP_CACHE( { 'file_name' => 'mbox.cache' }); my $folder_reader = new Mail::Mbox::MessageParser({ 'file_name' => $infile, 'enable_grep' => 1, }); die $folder_reader unless ref $folder_reader; # This is the main loop. It's executed once for each email while(!$folder_reader->end_of_file()){ my $rawemail = $folder_reader->read_next_email(); my $email = Email::MIME->new($rawemail); $email->body_set("New Body Text"); print $email->as_string

but it seems to ignore the new body..

If I include EMail::MIME:Modifier, the text "New Body Text" is printed, but no attachments....

How do I do this?

Thanks!

Replies are listed 'Best First'.
Re: Email::Mime Confusion
by saberworks (Curate) on Oct 06, 2009 at 15:40 UTC
    I dug around in the source of Email::MIME and Email::Simple a bit. Email::MIME inherits from Email::Simple. Email::Simple has a body_set function that sets an object var, "body" (key in blessed hash ref). The "as_string" method in Email::MIME overrides the one in Email::Simple. The one in Email::MIME looks at the "body_raw" object var (key in blessed hash ref). So when you call body_set(), it sets "body" but when you call as_string, it doesn't look for "body" it looks for "body_raw" instead.

    There are a number of things you can do. You can subclass Email::MIME and create a sub, body_set, that sets "body_raw" AND "body" so you're compatible with both. Or you can override as_string to print the one from body_raw instead. Instead of using "as_string" you can just print the headers then body yourself, using the headers and "body" joined by a newline.

    From Email::MIME:
    sub as_string { my $self = shift; return $self->__head->as_string . ($self->{mycrlf} || "\n") # XXX: replace with ->crlf . $self->body_raw; }
    From Email::Simple:
    sub as_string { my $self = shift; return $self->header_obj->as_string . $self->crlf . $self->body; }