Yii2 SwiftMailer通过远程smtp服务器(gmail)发送电子邮件
我想通过我的gmail帐户发送电子邮件 我的邮件配置:Yii2 SwiftMailer通过远程smtp服务器(gmail)发送电子邮件,yii2,swiftmailer,Yii2,Swiftmailer,我想通过我的gmail帐户发送电子邮件 我的邮件配置: [ 'class' => 'yii\swiftmailer\Mailer', 'useFileTransport' => false,//set this property to false to send mails to real email addresses 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'smt
[
'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();
}
}
我认为您错误地配置了邮件程序。因为它仍然使用默认的邮件功能。从下表可以看出,配置应如下所示。邮件器应位于组件中
'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”。Yii2具有不同的web和控制台配置文件。因此,您需要同时配置它们。关于这个问题,我必须创建邮件配置文件(例如mailer.php
),并将其包含在两个配置文件(web.php和console.php)中,如:
可能对某些人有用,作为参考:
'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,
],
]
],
]
您确定此电子邮件组件配置是针对键“mailer”的吗?根据此配置,它甚至不应该尝试发送电子邮件,因为“'useFileTransport'=>true”意味着它只将消息保存到file.oops。我忘了命令有自己的配置文件,而不是web.php。现在mailer工作正常了。@zeiz如果你找到了解决方案,请将其作为答案发布并接受。所以这对其他人是有帮助的。。
'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,
],
]
],
]