A cleaner way to send emails

CakePHP 1.2 provides a very easy way to send emails using the built-in Email component. However, sending emails directly from your User’s controller add action, for example, is somewhat ugly. It’s better to write a custom method in your app controller to handle the sending of emails.

Here’s an example, add this to your app controller:

[sourcecode language=’php’]
function _sendEmail($templateName,
$from = ‘My emailer ‘,
$replyToEmail = ‘noreply@yourdomain.com’,
$sendAs = ‘both’ ) {

$this->Email->to = $to;
$this->Email->subject = $emailSubject;
$this->Email->replyTo = $replyToEmail;
$this->Email->from = $from;
$this->Email->template = $templateName;
$this->Email->sendAs = $sendAs;

return $this->Email->send();

(Update: Thanks Jan Seidl for suggesting the return for this function, so that the response can be captured).

Note: don’t forget to add var $components = array(‘Email’); to your app controller as well.

The first three params you pass to the _sendEmail() method are likely to change, so we’ll pass those first. The rest you can set as defaults and only pass them if the defaults need to be changed.

Now, using the example of User controller add action, you can send the email using something like:

[sourcecode language=’php’]
$this->_sendEmail(‘user_reg’, ‘User registration’, $this->data[‘User’][’email’]);

It is very likely that you’d want to set some variables to be sent in the email. Well, setting the variables for the email is just the same as you would for any view (after all the email template is a view). So before calling _sendEmail() you might do:

[sourcecode language=’php’]
$this->set(’email’, $this->data[‘User’][’email’]);

Now the $email variable is available for use in your email template.

Using this approach keeps your controller’s action nice and clean.

P.S. You want to keep this method protected by prefacing the name with a “_”, so that it cannot be accessed by the URL. It is always a good idea to do so for any utility functions that need not to be accessed by the URL.

Related Posts