Easy text/html Multipart E-mails with Email::Simple::Markdown

May 16, 2012 / By Yanick Champoux

Tags: ,

These days, I go with Email::Simple to craft basic e-mails. For the more heavy stuff with attachments and what-not, I reach out to Email::MIME. Together, they make a pretty awesome duo. But… (Come on, admit it. You knew there was going to be a ‘but’.)

But there is a fairly common use-case that falls pretty much squarely between these two modules. Namely, creating multipart e-mails that have two versions of the same body: one that is normal, boring pure text, and the other that is pretty html. Email::Simple does not support multipart bodies (because, after all, it’s meant to be simple), so it cannot help me there. Email::MIME, though, is perfectly up for the job:

use Email::MIME;

my $email = Email::MIME->create(
    attributes => {
        content_type => 'multipart/alternative',
    },
    header_str => [
        From    => 'me@here.com',
        To      => 'you@there.com',
        Subject => q{Here's a multipart email},
    ],
    parts => [
        Email::MIME->create(
            attributes => { content_type => 'text/plain' },
            body => 'Howdie',
        ),
        Email::MIME->create(
            attributes => { content_type => 'text/html' },
            body => '<b>Howdie</b>',
        )
    ],
);

say $email->as_string;

It’s not atrocious, but it’s not lightweight either. And there is the problem that one has to make the effort to keep both bodies in sync. For simple e-mails, it would make much more sense to have a single source for the body and generate both renditions off it. For that kind of thing, Markdown served me well in the past, so why not use it? To my great pleasure, I found out that Email::MIME::Kit::Assembler::Markdown already exists. Alas, it’s also quite more heavy that I would like for the user-case at hand.

So I created Email::Simple::Markdown. (Again, raise your hand if you didn’t see that coming.)

It inherits from Email::Simple, and all it does is generate the multipart message out of an original pure-text body via the goodness of Text::MultiMarkdown. Nothing arcane, but with it the code above can now be reduced to:

use Email::Simple::Markdown;

my $email = Email::Simple::Markdown->create(
    header => [
        From    => 'me@here.com',
        To      => 'you@there.com',
        Subject => q{Here's a multipart email},
    ],
    body => '**Howdie**',
);

say $email->as_string;

This, I daresay, is much easier on the eyes.

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>