Yii2.0 邮件配置

在配置文件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文件夹下生成邮件模板文件,但并未发送。

mailer

此时,debug出Yii::$app->mailer的信息:

useFileTransport

可以看到该参数为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模板文件

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值