【问题标题】:Yii2 SwiftMailer sending email via remote smtp server (gmail)Yii2 SwiftMailer 通过远程 smtp 服务器(gmail)发送电子邮件
【发布时间】:2015-04-12 18:10:48
【问题描述】:

我想通过我的 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',
    ],
]

我写了命令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();
    }
}

当我尝试运行时:php yii mail

我得到:sh: 1: /usr/sbin/sendmail: not found

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

【问题讨论】:

  • 您确定此电子邮件组件配置用于密钥“邮件程序”吗?根据这个配置,它甚至不应该尝试发送电子邮件,因为“'useFileTransport' => true”意味着它只将消息保存到文件。

标签: yii2 swiftmailer


【解决方案1】:

我认为您错误地配置了邮件程序。因为它仍然使用默认的邮件功能。从documentation 开始,配置应如下所示。邮件应该在components 内。

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

另一个建议是使用端口“465”和加密作为“ssl”而不是端口“587”,加密“tls”。

【讨论】:

  • 哎呀。我忘记了命令有自己的配置文件,而不是 web.php。现在邮件程序工作正常。
  • @zeiz 如果您找到了解决方案,请将其作为答案发布并接受。所以它会对其他人有所帮助..
【解决方案2】:

Yii2 有不同的 web 和控制台工作配置文件。所以你需要配置他们两个。关于这个问题,我必须制作邮件配置文件(例如mailer.php)并将其包含在两个配置文件(web.php & console.php)中,例如:

'components' => [
    ...
    'mailer' => require(__DIR__ . '/mailer.php'),
    ...
],

【讨论】:

    【解决方案3】:

    可能对某人有用作为参考:

    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'viewPath' => '@common/mail',
        'useFileTransport' => false,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'username',
            'password' => 'password',
            'port' => 587,
            'encryption' => 'tls',
            'streamOptions' => [ 
                'ssl' => [ 
                    'allow_self_signed' => true,
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                ],
            ]
        ],
    ]
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2013-03-13
      • 2014-10-15
      • 2023-03-08
      • 2018-10-17
      • 1970-01-01
      • 2016-09-07
      相关资源
      最近更新 更多