Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Sending email

A site sends emails: a registration confirmation, a notice about a comment. In CakePHP the Mailer class is responsible for this. The delivery method, called a transport, is set in the configuration, and the text of a message is written as a template, like a page.

Setup

The transport is described in the EmailTransport section. The mail server parameters go into config/app_local.php:

// config/app_local.php
'EmailTransport' => [
    'default' => [
        'className' => 'Smtp',
        'host' => 'smtp.example.com',
        'port' => 587,
        'username' => 'blog@example.com',
        'password' => 'secret',
        'tls' => true,
    ],
],

The default sender address is set by the Email section in config/app.php: the from key of the default profile.

A simple message

// src/Controller/ArticlesController.php
use Cake\Mailer\Mailer;
 
$mailer = new Mailer('default');
 
$mailer
    ->setTo('anna@example.com')
    ->setSubject('New article')
    ->deliver('A new article has been published in the blog.');

Mailer('default') takes the default profile from the configuration. deliver() sends a message with the given text. Put the code into the add() action after a successful save and the address receives an email.

Your own mailer class

Messages of one area are collected in a class in the src/Mailer folder:

bin/cake bake mailer User
// src/Mailer/UserMailer.php
namespace App\Mailer;
 
use App\Model\Entity\User;
use Cake\Mailer\Mailer;
 
class UserMailer extends Mailer
{
    public function welcome(User $user): void
    {
        $this
            ->setTo($user->email)
            ->setSubject('Welcome')
            ->setViewVars(['user' => $user]);
    }
}

Each method is one message. setViewVars() passes variables to the email template, like set() in a controller.

The email template

The template is named after the method. Create templates/email/text/welcome.php:

Hello!
 
You have registered in the blog with the address <?= $user->email ?>.

This is a plain text message, so it has no tags. For a message with markup create a second file, templates/email/html/welcome.php, and call setEmailFormat('both') in the method.

Sending

// src/Controller/UsersController.php
use Cake\Mailer\MailerAwareTrait;
 
class UsersController extends AppController
{
    use MailerAwareTrait;
 
    public function add()
    {
        // ... saving the user
 
        $this->getMailer('User')->send('welcome', [$user]);
    }
}

getMailer('User') creates UserMailer, and send() calls the welcome() method with the arguments from the array and sends the message. After registration the user receives a greeting.

Message methods

MethodWhat it sets
setTo(), setCc(), setBcc()Recipients
setFrom()The sender
setSubject()The subject
setEmailFormat('html')The format: text, html, both
setAttachments(['/path/file.pdf'])Attachments

Common mistake

A developer's computer usually has no mail server, and sending ends with a connection error. For development set the transport to 'className' => 'Debug': the message goes nowhere and its content is returned by the send() method, an array with the headers and message keys that can be printed with debug().

Thanks for reading!

Donate to the site — we work hard for you.