Yii2 SwiftMailer通过远程smtp服务器(gmail)发送电子邮件

Zei*_*eiZ 3 swiftmailer yii2

我想通过我的Gmail帐户发送电子邮件.

我的邮件配置:

[
'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',
    ],
]
Run Code Online (Sandbox Code Playgroud)

我写了命令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();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我试图跑: php yii mail

我明白了: sh: 1: /usr/sbin/sendmail: not found

但是为什么它需要sendmail,如果我只想要连接到smtp.gmail.com的SMTP?

Mah*_*rai 15

我认为你错误地配置了邮件程序.因为它仍然使用默认的邮件功能.从文档中,配置应如下所示.邮件应该在里面components.

'components' => [
    ...
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'username',
            'password' => 'password',
            'port' => '587',
            'encryption' => 'tls',
        ],
    ],
    ...
],
Run Code Online (Sandbox Code Playgroud)

还有一个建议是使用端口"465"和加密作为"ssl"而不是端口"587",加密"tls".

  • @zeiz如果您找到了解决方案,请将其作为答案发布并接受.所以对其他人有帮助.. (2认同)