Wednesday, January 27, 2010

Using Textile for HTML E-mail Generation

These days, HTML e-mail is the norm for PHP apps I develop - which means I'm using PHPMailer instead of the old fashion built-in mail() function call. PHPMailer makes it easy to send HTML messages, you just set the Body property on the mailer object, and tell it that is in fact HTML:

 $mailer = new PHPMailer();
 $mailer->Body = "...HTML Formatted Message...";
 $mailer->IsHTML(true);

All easy enough. Though, I was wondering if there was a more concise way to manage the HTML messages themselves. While playing with Perch, I re-remembered the joy of using Textile - a lightweight markup language that reads like text, yet can be turned into HTML. Then it hit me, why I don't I maintain my messages in my code in Textile and then convert them to HTML on the fly?

This turns out to be super easy to do. First, you write some Textile:

$subj = "Thanks For Signign Up For Foo!.com";
$body = <<<EOF
Hello _{$username}_,

Thanks so much for signing up for "Foo!.com":http://www.fooexclamationpoint.com

Your account is just about ready for you to use. You just need to confirm the account.
You can do this by clicking "here":$confirmation_url or, you can click on the link below:

p=. "$confirmation_url":$confirmation_url

Thanks for joining up and have a Foo!tastic day.

Foo!.com(c)
EOF;

Now, you can transform the Textile to HTML and store the value on the mailer:

$t = new Textile();
$mailer = new PHPMailer();
$mailer->IsHTML(true);
$mailer->Subject = $subj;
$mailer->Body = $t->TextileThis($body);
$mailer->AltBody = $body;

You can see, in the last line, I store the textile input as the text version of this mail message. While not perfect, the Textile version should at least be a readable version of the message for the few folks out there without HTML capability.

So there you have it, concise messages to maintain, pretty HTML formatted e-mails, and a passable alt-version of HTML all in about 3 lines of extra code.

No comments:

Post a Comment