Search code examples
yii2swiftmailer

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' => 'my@gmail.com',
    '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 = 'my@gmail.com';
    private $to = 'to@gmail.com';

    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?


Solution

  • 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".