在配置文件main.php 或 params.php 文件配置相关项。
'mailer' => [
'class' => 'yii\swiftmailer\Mailer', #必不可少
'viewPath' => '@common/mail', #邮件模板路径
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.163.com', #163 SMTP邮件服务器
'username' => 'xxx@163.com', #邮箱
'password' => 'xxxxxxx', #163服务器,请设置安全密码
'port' => '465', #465/994
'encryption' => 'ssl', #采用ssl加密方式
],
],
测试方式:
$mailer = Yii::$app->mailer
$mailer->compose()
->setFrom('aaa@163.com')
->setTo(‘bbb@qq.com’)
->setSubject('邮箱验证')
->send();
这样就会想setTo指定的邮箱发送邮件。
但是当执行测试代码时,会发现send返回结果为true,但是setTo邮箱并没有收到邮件。那么原因在于参数useFileTransport没有设置正确,看文档解释:
Whether to save email messages as files under $fileTransportPath instead of sending them to the actual recipients. This is usually used during development for debugging purpose.
public boolean $useFileTransport = false
该参数决定是否真正的发送给收件人,常用于开发测试。如果为true,会在runtime下的mail文件夹下生成邮件模板文件,但并未发送。
此时,debug出Yii::$app->mailer的信息:
可以看到该参数为true,因此收不到邮件。可以通过以下两种方式实例化Mailer类:
1.把Yii::$app->mailer的该参数设置为false;
$mailer = Yii::$app->mailer;
$mailer->useFileTransport = false;
$res = $mailer->compose()->setFrom('xxx@163.com')->setTo('xxxx@qq.com')->setSubject('邮箱验证')->send();
var_dump($res);
2.实例化自行Mailer类,并设置transport参数项
$mailer = new \yii\swiftmailer\Mailer();
$mailer->transport = Yii::$app->params['mailer']['transport'];
#注意,需要在config文件夹下的params文件中配置文章开始的mailer项
$res = $mailer->compose() ->setFrom('xxx@163.com')->setTo('xxx@qq.com')->setSubject('邮箱验证')->send();
这样邮件就会发送成功,设置发件人别名:
->setFrom(['xxx@163.com' => '别名'])
注意:
1. 配置文件中的密码对于163来说不是邮箱密码,而是邮箱开通smtp的安全密码。
2. 指定发送邮件的模板在compose(‘test’)中,在common/mail文件夹下需要有test.php模板文件