http://qs321.pair.com?node_id=92778


in reply to Net::SMTP and templates/ here docs

boo_radley I feel your pain. But I'd like to make an argument against using here doc syntax, or constructing email messages by hand.

A while ago I decided that it just wasn't (time) efficient to mess with lower level details when I don't have to. Sure, I know how to construct a raw email message by hand, or speak to an SMTP server directly, etc, but why would I want to keep repeating the same code or logic over and over in my programs when CPAN modules would deal with all the details for me.

My personal philosophy is to not deal with implementation specific details as much as possible. That's not to say that I don't see the value in learning how these protocols work, I do - it is very valuable, especially during debugging. But, I just don't see the value in re-inventing the wheel, or trying to remember every little implementation detail, each time I need to engineer something.

This means when I make CGI's, I use CGI.pm. When I parse HTML, I use HTML::Parser. And when I need to create a message body I use a combination of Mail::Header and Mail::Internet to both construct and email it.

The benefit of using those modules is that they have utility methods that wrap around Net::SMTP. Once you build the message, it's just a matter of a few lines of code to send it out. Here's a short, working, example of how I use them:

#!/usr/bin/perl -wT use strict; use Mail::Address; use Mail::Header; use Mail::Internet; use Net::SMTP; use constant SMTP_HOST => 'smtp.domain.com'; #Build the Email Addresses my $to = Mail::Address->new('Firstmame Lastname', 'user@domain.com') +; my $from = Mail::Address->new('My Name', 'me@domain.com'); #Build the Headers my $header = Mail::Header->new; $header->add(To => $to->format); $header->add(From => $from->format); $header->add(Subject => 'test subject'); #Build the Message my $mail = Mail::Internet->new( Header => $header, Body => ['test body string, or an arrayref of body lines'], ); #Send the Message $mail->smtpsend(Host => SMTP_HOST) or die 'Could not send message to ', $to->format;

The above code, while it may not be perfect, illustrates my point. We've taken ourselves farther away from the specifics of constructing the email body, right down to dealing with only the important information. All specifics about how the emails addresses, headers, body, and how SMTP works are hidden from you.

IMHO, one of the biggest benefits of this is that all the methods are documented and tested. Ever try to read an official RFC from beginning to end? Do still you remember every detail? Yeah, me neither. =) You won't need to, for example, just type perldoc Mail::Internet and you can read about how to use the smtpsend() method without worrrying about details regarding the SMTP protocol. Besides, I shudder to think of how many RFC's you'd need to memorize in order to duplicate just the short example snippet I posted above.