Skip to content
CODE THE PIXEL
CakePHP

CakePHP 4 Sending Email

Asyraf Wahi Anuar Updated 3 min read

Send email from CakePHP 4 using email class. This tutorial will show how to configure and send email using CakePHP 4.

This tutorial may be outdated

It was last reviewed 4 years ago. Some steps may differ in newer versions.

Tech stack

  • CakePHP 4.x

Sending email in CakePHP is simple and easy. Mailer class makes the email sending process very convenient. Using Mailer, the developer can configure and send email from any place inside your application. Email can be used to send a notification to a user or moderator regarding the new registration, contact support, mailing list etc. The developer needs to have a valid email to ensure that the sent email is not going to the spam folder.

Email Transport Configuration

Set your email account as follows. This email configuration will be used to send emails to the newly registered user and password reset requests.

config/app_local.phpPHP
'EmailTransport' => [
    'smtp' => [
        'host' => 'YourHostName', //eg: codethepixel.com
        'port' => 26,
        'username' => 'EmailAddress', //eg: admin[at]codethepixel.com
        'password' => 'Secret', //email password
        'className' => 'Smtp',
        'client' => null,
        'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
    ],
],

or you can use a Gmail account. However, it required you to allow less secure app access in your Google account setting to allow your Gmail to be accessed from your localhost. Refer to the Google announcement here.

PHP
'EmailTransport' => [
    'gmail' => [
        'host' => 'smtp.gmail.com',
        'port' => 587,
        'username' => 'YourGmailAddress', //eg: sample[at]gmail.com
        'password' => 'Secret', //email password
        'className' => 'Smtp',
        'tls' => true,
        'client' => null,
        'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
    ],
],

Configure Email Class

Load the email class at the beginning of the controller. This tutorial used the 'user' table as a reference.

src/Controller/UsersController.phpPHP
use Cake\Mailer\Email;
use Cake\Mailer\Mailer;
use Cake\Mailer\TransportFactory;

Send Email Without Template

In this tutorial, we assumed that when the user completed the registration process, an email will be sent to their registered email account. The name and email variable are requested to be used in the email content. Then using the $mailer, the developer needs to identify the email transport (SMTP or Gmail or others transport that has been configured), sender, receiver, format, subject and content of the email as shown below:

src/Controller/UsersController.phpPHP
public function add()
{
    $user = $this->Users->newEmptyEntity();

    if($this->request->is('post')){
        $userTable = TableRegistry::get('Users');
        $name = $this->request->getData('name');
        $email = $this->request->getData('email');
        $user = $userTable->newEntity($this->request->getData());
            if($userTable->save($user)){
                $user->name = $name;
                $user->email = $email;
                
                $mailer = new Mailer('default');
                $mailer
                    ->setTransport('smtp'); //your email configuration name
                    ->setFrom(['noreply[at]codethep!xel.com' => 'Code The Pixel'])
                    ->setTo($email)
                    ->setEmailFormat('html')
                    ->setSubject('Verify New Account')
                    ->deliver('Hi $name<br/>Welcome to Code The Pixel.');
                
                $this->Flash->success(__('Your account has been registered.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('Registration failed, please try again.'));
            }
    }
    $this->set(compact('user'));
}

Send Email Using Template

Developer can create a email template in ...\templates\email\html\new_user.php and used the value from $setViewVars. The configuration is shown as follows:

templates/email/html/new_user.phpPHP
public function add()
{
    $user = $this->Users->newEmptyEntity();
    if($this->request->is('post')){
        $userTable = TableRegistry::get('Users');
        $name = $this->request->getData('name');
        $email = $this->request->getData('email');
        $user = $userTable->newEntity($this->request->getData());
            if($userTable->save($user)){
                $user->name = $name;
                $user->email = $email;
                
                $mailer = new Mailer('default');
                $mailer
                    ->setTransport('smtp'); //your email configuration name
                    ->setViewVars([ //email view variables
                        'name' => $name,
                        'email' => $email,
                        ])
                    ->setFrom(['noreply[at]codethep!xel.com' => 'Code The Pixel'])
                    ->setTo($email)
                    ->setEmailFormat('html')
                    ->setSubject('Verify New Account')
                    ->viewBuilder()
                        ->setTemplate('new_user');
                $mailer->deliver();
                
                $this->Flash->success(__('Your account has been registered.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('Registration failed, please try again.'));
            }
    }
    $this->set(compact('user'));
}

Example of Email Template (new_user.php)

PHP
Hi <?= $name; ?>,<br/>Welcome to Code The Pixel.

You also can refer CakePHP cookbook for more details. That's all. Happy coding :)

Did this tutorial help?

197 readers found this helpful

Comments

No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

Using Bahasa Melayu Table Names in CakePHP

Learn how to use Bahasa Melayu table names like "pengguna" in CakePHP while following the framework’s naming conventions. Includes tips for using the Bake tool and avoiding pluralization issues.

5 min read

Tools & Software

Formatting PHP in VSCode Using Prettier and PHP Intelephense

Learn how to set up Visual Studio Code (VSCode) for automatic PHP file formatting using the Prettier and PHP Intelephense extensions. This step-by-step tutorial will help you maintain a clean and organised codebase, enhancing your PHP development experience.

2 min read