Email Templates with CodeIgniter

The more I use it, the more and more I love CodeIgniter as a framework; in fact I believe I cherish it more than CakePHP due to it’s simplicity. One thing that I do like about CakePHP is that by mixing in PHPMailer you get the ability to specify views for your html email and [...]

The more I use it, the more and more I love CodeIgniter as a framework; in fact I believe I cherish it more than CakePHP due to it’s simplicity. One thing that I do like about CakePHP is that by mixing in PHPMailer you get the ability to specify views for your html email and views for your text emails. So you could have multipart emails being sent based off the data in these views.

Sadly, this is one thing that CodeIgniter is lacking. But if you look around the docs long enough (which are absolutely fantastic by the way) you’ll see that you can use CodeIgniter’s built in template parsing class to do the same thing.

Let’s assume that we are building a site that allows users to create an account. When they create an account, they need to get a welcome email from the application. I’m going to assume you know how to build the form and process the data so here’s the controller action that handles the mail part of things.


function signup(){

#stripped out the validation code

#stripped out the db insert code

$data = array(
'some_var_for_view'=>'Some Value for View'
);

$htmlMessage =  $this->parser->parse('user/email/signup_html', $data, true);
$txtMessage = $this->parser->parse('user/email/signup_txt',  $data, true);

#send the message
$this->email->from('', 'CSSNinja');
$this->email->to($this->input->post('email_address'));
$this->email->subject('Account Registration Confirmation');
$this->email->message($htmlMessage);
$this->email->alt_message($txtMessage);
$this->email->send();

}

Nothing really ground breaking going on here, but notice the two lines that declare the variables $htmlMessage and $txtMessage, these two lines are what’s going to allow us to use these views as email templates.

The template parsing class will parse out a template using the following syntax:

$this->parser->parse('path/to/view',$data_array);

However, if you pass a true value as an optional third parameter (default is false) CodeIgniter does not render the view, it returns its fully parsed text as a string. So the $htmlMessage variables and $txtMessage variables now hold appropriately formatted code for either a text message or an html message which is exactly what CodeIgniter’s email function needs for its message() and alt_message() methods.

Hope this was helpful, post any questions, concerns or moral outrages in the comments.