24 days of Perl code from RJBS! Feed

E-mail Made Simple

E'Mail::Acme - 2009-12-12

Okay, I Lied

I got a decent amount of angry comments on Thursday's post about Email::MIME::Kit. It seems people are sick of my insistance that e-mail is really complicated and they want me to publicly admit that it's simple.

I admit it. E-mail is pretty much just a dumped hash, then a bunch of lines, and maybe some attached files at the end. I've written some code to show off how easy things can be, if you just accept that e-mail is simple. This code is the acme of simplicity and the acme of utility.

It doesn't use any objects or special variables or functions. It just lets you put data into a structured variable, and then you can send it.

E'Mail::Acme

Setting up the Header


1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
10: 
11: 
12: 

 

use E'Mail::Acme;

my $e_mail = E'Mail::Acme;

# Now we have our e-mail variable, so we can put some headers in it.
# Headers are just a hash, remember?

$e_mail->{From} = q<Ricardo Signes <rjbs@example.com>>;

# ...and we can get multiple headers easily enough, just assign a few times:
$e_mail->{To} = q<Santa Claus <santa@north-pole.mil>>;
$e_mail->{To} = q<Kris Kringle <kk@macys.com>>;

 

So, easy! The header is just a hash, like you'd expect.

Setting up the Body

The body is just a bunch of lines of text. In other words, an array. We can add lines easily enough.


1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 

 

push @$e_mail, "Dear Santa,"
             , ""
             , "Here are some things I want:"
             , @things_i_want
             , ""
             , "Please gimme."
             , ""
             , "-- "
             , "rjbs";

 

Great. Of course, that looks pretty ridiculous. Probably we wanted to just do this:


1: 
 

push @$e_mail, `cat /tmp/mutt-terrordome-2608-9063-429`;
 

And just to show that we're not limited to the world of boring "single part" e-mails, we'll attach a little incentive.


1: 
2: 
3: 
4: 
5: 
6: 
7: 

 

# first, we make an attachment
my $attach = E'Mail::Acme;
$attach->{'content-type'} = 'image/jpeg';
push @$attach, `cat amazon-giftcert.jpg`;

# then we attach it
push @$e_mail, $attach;

 

Sending our Message

Sure, we could bring in some modern, best-practice library like Email::Send:


1: 
 

Email::Send->new->send("$e_mail");
 

...but we'd just be back to these ridiculous object-oriented interface that clutter up our simple e-mail handling. We set up our e-mail object, and now we want to do something with it. There's only one thing we do with e-mail, right? We send it! All we have to do is tell Perl we want to do (that thing with) the e-mail:


1: 
 

do &$e_mail;
 

We could also have written $e_mail->(), but the arrow notation unnecessarily reminds me of objects, so I try to avoid it.

Sane, Simple, Sensisble

So, there you have it. E-mail handling made simple and straightforward, just like you'd like it. Use it everywhere!

See Also