CakePhp 3.x | Send Email using SMTP

| By Webner

To send an email in cakephp use Email class of Cakephp 3. In app.php under config folder, add a new entry in the table EmailTransport.

For example here ‘mail’. Specify host, port, username and password in it:

'EmailTransport' => [
        'default' => [
            'className' => 'Mail',
            // The following keys are used in SMTP transports
            'host' => 'localhost',
            'port' => 25,
            'timeout' => 30,
            'username' => 'user',
            'password' => 'secret',
            'client' => null,
            'tls' => null,
            'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
            ‘mail’=> [
                    'host' => '',
                    'port' => 587,
                    'username' =>xxxxx', //gmail id
                    'password' =>xxxxx, //gmail password
                    'tls' => true,
                    'className' => 'Smtp'

Now in Controller, the function to send email uses above-written entry in transport() function as below.

Add path in controller- use Cake\Mailer\Email:

function sendEmail()
           $message = "Hello User";            
            $email = new Email();
            $email->from(['Sender_Email_id' => 'Sender Name'])
            ->subject(‘Test Subject’)
            ->attachments($path) //Path of attachment file


One comment

Leave a Reply

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