CakePHP | Send Email using SMTP in cakephp 3

|
| By Webner

1. Open config/app.php file inside your project and then modify the default email configuration and setup your SMTP account there:

'EmailTransport' => [
'default' => [
'className' => 'SMTP',
// The following keys are used in SMTP transports
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'timeout' => 30,
'username' => 'abc@gmail.com', // valid email account
'password' => '********', // valid account password 
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],

2. Make a new subfolder Mailer in your src directory Mailer. Create the file inside Mailer folder. The file you will add inside Mailer folder should have suffix Mailer as per CakePHP conventions. You can send images as the attachment via email. To do this I have added a subfolder named files inside webroot img folder. I have added my images to files folder. In the below code I have used those images to send via email attachment. Below is my sample code for UserMailer.php:

<?php
namespace App\Mailer; 
use Cake\Mailer\Mailer;    
class UserMailer extends Mailer
{
public function registered($user)
{
// attach a text file 
$this->attachments([
// attach an image file 
'edit.png'=>[
'file'=>'files/welcome.png',
'mimetype'=>'image/png',
'contentId'=>'734h3r38'
]
])
->to($user->email) // add email recipient
->emailFormat('html') // email format
->subject(sprintf('Welcome %s', $user->name)) //  subject of email
->viewVars([   // these variables will be passed to email template defined in step 5 with 
//name registered.ctp
'username'=> $user->name,
'useremail'=>$user->email
])
// the template file you will use in this email
->template('registered') // By default template with same name as method name is used.
// the layout  'default.ctp’ file you will use in this email
->layout(default); //optional field
}}

3. After that goto src/template folder. You will see two subfolders there: 1) Email 2) Text.  Inside HTML folder create file Registered.ctp. You can define your email template here:

Sample Registered.ctp         
<p>Hello  <?=$username?> < <?=$useremail?> ></p>
<p>
Welcome to Our web site .We hope you enjoy our services :<br>
<br>
</p>
<p>
You were registered successfully:
<img src='cid:734h3r38'  />
</p>

4. Inside text folder create file default.ctp:

<?php <?= $content ?> ?>

This page will simply render your email template content.

Below is my Controller code where I am calling email functionality:

<?php
namespace App\Controller;
use App\Controller\AppController;       
use Cake\Mailer\MailerAwareTrait;       //  Built in function use for sending multiple email
use Cake\Mailer\Email;                          // import email library
class UsersController extends AppController{
use MailerAwareTrait;
public function add()
{
$email = new Email('default');     
$email->from(['you@example.com' => 'My Site'])      // sender email
->to('yourcolleage@example.com') // receiver email
->cc('yourmanager@example.com') //  cabron copy email (optional)
->bcc('anothercolleage@example.com') // blind carbon (optional)
->subject('About')   // message subject        
->replyTo('you@example.com') // email to reply to  
/* Sending emails using reusable emails.
$this->getMailer('User')->send('registered', [$user]);
 }
?>

Explanation:

$this->getMailer(‘User’)->send(‘registered’, [$user]); The above code line is doing the main stuff to send email.

$this->getMailer(‘User’): It is calling our custom defined mailer in the step 2 with name ‘UserMailer.php’.

send(‘registered’, [$user]); This piece of code is calling registered function defined inside ‘UserMailer.php’ file and passing $user object as an argument to the function which is used then to fill data inside email template defined with the name “registered.ctp’.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *