Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 SwiftMailer sending email via remote smtp server (gmail)

I want to send emails via my gmail account.

My mailer config:

[
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,//set this property to false to send mails to real email addresses
'transport' => [
    'class' => 'Swift_SmtpTransport',
    'host' => 'smtp.gmail.com',
    'username' => '[email protected]',
    'password' => 'pass',
    'port' => '587',
    'encryption' => 'tls',
    ],
]

I wrote command MailController:

<?php

namespace app\commands;

use yii\console\Controller;
use Yii;

/**
* Sanding mail
* Class MailController
* @package app\commands
*/
class MailController extends Controller
{
    private $from = '[email protected]';
    private $to = '[email protected]';

    public function actionIndex($type = 'test', $data = null)
    {
        Yii::$app->mailer->compose($type, ['data' => $data])
            ->setFrom($this->from)
            ->setTo($this->to)
            ->setSubject($this->subjects[$type])
            ->send();
    }
}

When I'm trying to run: php yii mail

I get: sh: 1: /usr/sbin/sendmail: not found

But why it requires sendmail if I want just SMTP connection to smtp.gmail.com?

like image 731
ZeiZ Avatar asked Nov 29 '22 10:11

ZeiZ


1 Answers

I think you have configured the mailer wrongly. Because it is still using the default mail function. From the documentation the configuration should be like below. The mailer should be inside components.

'components' => [
    ...
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'username',
            'password' => 'password',
            'port' => '587',
            'encryption' => 'tls',
        ],
    ],
    ...
],

One more suggestion is to use port "465" and encryption as "ssl" instead of port "587", encryption "tls".

like image 152
Mahendran Sakkarai Avatar answered Dec 10 '22 16:12

Mahendran Sakkarai