About
Random notes: A pile of assorted scribblings, snippets and ramblings (mostly about programming and the software that makes my life easier).

Rhesa Rozendaal
Subscribe
Subscribe to a syndicated feed of my weblog.
Categories
Archive
November
Sun Mon Tue Wed Thu Fri Sat
 
29        
Links

2010. 11. 29

Email::MIME::* modules aren’t very close friends


The Email::* modules are all pretty neat, with a pleasant API. But combining them isn’t always as effortless as you’d expect.

For my email2blog script, I use Email::Filter as the bridge between the MTA and blosxom:

 # grab email from STDIN
 my $mail = Email::Filter->new;

The $mail object has nifty methods that make it very simple to accept or reject a message.

Once I accept a message, I take out the attachments with Email::MIME::Attachment::Stripper. The first step is to construct a stripper based on the incoming email:

 # make stripper
 my $strip = Email::MIME::Attachment::Stripper->new(
             Email::MIME->new( $mail->simple->as_string ),
             force_filename => 1
 );

I’m not impressed with the hoops I have to jump through there. It should be easy for EMA::Stripper to build its own Email::MIME object when handed an Email::Simple object. But in fact, even Email::MIME itself doesn’t offer that option.

Next up is taking apart the MIME email:

 # strip attachments
 my $msg = $strip->message;
 my @attachments = $strip->attachments;

That’s pretty straightforward. $msg is an Email::MIME object, without the attachments. To get at the plaintext body is still not very comfortable:

 # extract plaintext body
 my $text = first { $_->content_type =~ m{text/plain} } $msg->parts;

Maybe that’s because there may not be a text/plain part with meaningful content, but I wouldn’t expect $msg->body to be empty after the strip operation. It is though, so that fancy grep is necessary.

The @attachments array on the other hand is very easy to work with. It has just the things you need, and nothing else.

All in all, the script ended up being about 60 well-spaced lines long, with most of that being taken up by sanitizing the input. The fact that I didn’t actually have to think how MIME encoding works under the hood was a big plus, and for that I’m very happy with the PEP Project.


Comments are closed for this story.