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

Posted in: Technical Track

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:

[perl]use Email::MIME;

my $email = Email::MIME->create(
attributes => {
content_type => ‘multipart/alternative’,
},
header_str => [
From => ‘[email protected]’,
To => ‘[email protected]’,
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;
[/perl]

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:

[perl]use Email::Simple::Markdown;

my $email = Email::Simple::Markdown->create(
header => [
From => ‘[email protected]’,
To => ‘[email protected]’,
Subject => q{Here’s a multipart email},
],
body => ‘**Howdie**’,
);

say $email->as_string;

[/perl]

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

email
Want to talk with an expert? Schedule a call with our team to get the conversation started.

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *