CakePHP4 Mailer Usage - Email Transport Example

CakePHP4 Mailer Usage - Email Transport Example with GMail

The Email Transport functionality in the /config/app.php allows you to maintain consistent to/from information when sending emails in CakePHP.

in the example below, we use the "Email Transport" named "gmail-transport".  This transport holds our SMTP user and email login information.

We use the Email Delivery Profile named "gmail-delivery", to specify the transport ("gmail-transport"), from address (array in this case), and reply-to address (array in this case).

Note: you may need to go into your gmail account security settings, and allow less-secure apps.

Delivery Profile

'gmail-delivery' => [
     'transport' => 'gmail-transport',
     'from' => ['noreply@example.com'=>'DO NOT REPLY - Your From Name'],
     'replyTo' => ['noreply@example.com'=>'DO NOT REPLY'],
   ],

 

EmailTransport Profle

'gmail-transport' => [
     'className' => 'Smtp',
     'host' => 'smtp.gmail.com',
     'port' => 587,
     'timeout' => 30,
      'username' => 'your gmail address @gmail.com',
     'password' => 'your gmail password',
     'client' => null,
     'tls' => true,
     'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
    ],

 

Usage Example:

     $mailer = new Mailer('gmail-transport'); //new mailer object using 
     $mailer->setTo('recipient@example.com', 'Recipient Name');
     $mailer->setSubject('Your Email Subject' );
     $mailer->setEmailFormat('html');
     $mailer->viewBuilder()->setTemplate('template name');
     $mailer->viewBuilder()->setLayout('default');
     $mailer->setViewVars(['emailVariables' => $emailVariables]);
     //NOTE: IF YOU WISH TO VIEW THE EMAIL OUTPUT, UNCOMMENT THE LINES BELOW
     // Render the email
     //$mailer->render();
     //$emailContent = $mailer->getBody();
     //foreach($emailContent as $line) {
     //    echo $line;
     //}
     //​exit;

     //SEND THE EMAIL 
     return $mailer->deliver('default');
     

 

 

Share this Post