Sending Email in CakePHP3 & CakePHP4

Sending Email in CakePHP3 & CakePHP4

CakePHP3:

In your Controller:

use Cake\Mailer\Email;

In your Controller's method:

$email = new Email('default');
$email->sender('app@example.com', 'MyApp emailer');
$email->from(['me@example.com' => 'My Site'])
    ->to('you@example.com')
    ->subject('About')
    ->send('My message');      

 

CakePHP4:

use Cake\Mailer\Mailer;
$mailer = new Mailer('default');
$mailer->setFrom(['me@example.com' => 'My Site'])
    ->setTo('you@example.com')
    ->setSubject('About')
    ->deliver('My message');

 

Here's another CakePHP4 example, selecting the template (content) and the layout (content wrapper) for your email.  This also demonstrates using variables in the template; In this case, first_name and last_name:

$mailer = new Mailer('default');
$emailViewVars = ['first_name'=>'John', 'last_name'=>'Doe'];
$mailer->setFrom(['me@example.com' => 'Example.com'])
   ->setEmailFormat('html')
   ->setTo('destinationemail@example.com)
   ->setSubject('Email Subject')
   ->setViewVars($emailViewVars)
   ->viewBuilder()
      ->setTemplate('confirm_email')
      ->setLayout('default');
$mailer->deliver();

In the above example, here is an example of the confirm_email.php template, located in \templates\email\html\confirm_email.php

Dear <?= $first_name; ?> <?= $last_name; ?>,<br/><br/>
Welcome to Example.com!<br/><br/>
Please enjoy the website!<br/><br/>
Best Regards<br/>
The example.com team

Also, in the above example, here is an example of the default.php layout, located in \templates\layout\email\html\default.php
Note: this is the default CakePHP4 version of the file, without the copyright headers.

$content = explode("\n", $content);
foreach ($content as $line) :
    echo '<p> ' . $line . "</p>\n";
endforeach;

Share this Post