Mailer classes let you encapsulate related Email logic into a reusable
and testable class.
Defining Messages
Mailers make it easy for you to define methods that handle email formatting
logic. For example:
class UserMailer extends Mailer
{
public function resetPassword($user)
{
$this
->setSubject('Reset Password')
->setTo($user->email)
->set(['token' => $user->token]);
}
}
Is a trivial example but shows how a mailer could be declared.
Sending Messages
After you have defined some messages you will want to send them:
$mailer = new UserMailer();
$mailer->send('resetPassword', $user);
Event Listener
Mailers can also subscribe to application event allowing you to
decouple email delivery from your application code. By re-declaring the
implementedEvents() method you can define event handlers that can
convert events into email. For example, if your application had a user
registration event:
public function implementedEvents()
{
return [
'Model.afterSave' => 'onRegistration',
];
}
public function onRegistration(Event $event, Entity $entity, ArrayObject $options)
{
if ($entity->isNew()) {
$this->send('welcome', [$entity]);
}
}
The onRegistration method converts the application event into a mailer method.
Our mailer could either be registered in the application bootstrap, or
in the Table class' initialize() hook.
This object's primary model class name. Should be a plural form.
CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'.
Plugin classes should use Plugin.Comments style names to correctly load
models from the correct plugin.