Sunday, January 16, 2022

[FIXED] Cakephp 3 email with SMTP not working

Issue

I am trying to send an email from my CakePHP 3 application. But every time it is using the localhost SMTP and I am getting the error.

enter image description here

So here is my code.

public function sendEmail($email, $subject, $message){

        // Sample SMTP configuration.
        $this->loadModel('Generalsettings');
        $query = $this->Generalsettings->find('all')->where(['meta_key' => 'smtp_details'])->applyOptions(['default' => false]);
        $smtpdetail = $query->first();
        $detail = json_decode($smtpdetail->value);
        Email::configTransport('gmail', [
            'host' => $detail['host'], //value is 'ssl://smtp.gmail.com'
            'port' => $detail['port'], //value is 465
            'username' => $detail['username'],
            'password' => $detail['password'],
            'className' => 'Smtp'
        ]);
        $emailClass = new Email();
        $emailClass->from(['er.dhimanmanoj@gmail.com' => "Sender"])
             ->to($email)
             ->subject($subject)
             ->send($message);
    }

Please tell me if I am doing something wrong. Thanks in advance.


Solution

You haven't specified the transport you just created using configTransport() method. So it is taking the default settings from config/app.php.

You can setup transport like this:

$emailClass = new Email();
$emailClass->transport('gmail');

NOTE: Deprecated since version 3.4.0: Use setTransport() instead of transport().

For more info please refer to this link @https://book.cakephp.org/3.0/en/core-libraries/email.html

Hope this helps!



Answered By - Ishan

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.