如何在 Yii2 中使用 swiftMailer

2022-08-30 12:15:35

我最终无法理解如何在 Yii2 中使用 swiftMailer 扩展。从这个主题来看,我没有找到问题,任务是微不足道的,但直到最后我都无法理解。

有些例子没有更详细地描述发送信件的整个周期,或者我不明白一些:(

设置

    return [
    //....
   'components' => [
    ......
    'mail' => [
      'class' => 'yii\swiftmailer\Mailer',
      'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'localhost',
        'username' => 'username',
        'password' => 'password',
        'port' => '587',
        'encryption' => 'tls',
      ],
    ],
  ]
];

发送

Yii::$app->mail->compose()
->setTo($toEmail)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();

我希望收到一个具体的工作示例。谢谢。

附言:我调整了域名记录MX,DKIM,SPF添加。

UPD(一些答案)

在“发件人”字段中传递的电子邮件,默认情况下将其放在“返回路径”字段中,必须是现有地址。某些提供商不允许从不存在的电子邮件地址发送邮件。


答案 1

确保已在生产环境中初始化应用程序以从应用程序发送电子邮件,否则它将被写入 mailoutput 文件夹。或者手动编辑配置文件,如下所示。

在组件的公共/主本地部分.php

'mail' => [
        'class' => 'yii\swiftmailer\Mailer',
        'viewPath' => '@backend/mail',
        'useFileTransport' => false,//set this property to false to send mails to real email addresses
        //comment the following array to send mail using php's mail function
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'username@gmail.com',
            'password' => 'password',
            'port' => '587',
            'encryption' => 'tls',
            ],
    ],

在控制器中

    \Yii::$app->mail->compose('your_view', ['params' => $params])
    ->setFrom([\Yii::$app->params['supportEmail'] => 'Test Mail'])
    ->setTo('to_email@xx.com')
    ->setSubject('This is a test mail ' )
    ->send();

这应该有效!希望这会对您有所帮助!


答案 2

您不需要将SMTP传输与swiftmailer一起使用,只需在配置文件中删除(在基本模板中),邮件就会流动。'useFileTransport' => trueapp/config/web.php

查看文档:

http://www.yiiframework.com/doc-2.0/ext-swiftmailer-index.html


推荐