当前位置:Gxlcms > PHP教程 > Yii2邮件发送出现问题怎么解决

Yii2邮件发送出现问题怎么解决

时间:2021-07-01 10:21:17 帮助过:25人阅读

刚刚用了一下yii邮件发送功能,虽然结果返回成功,但接收不到邮件。配置文件代码如下:

  1. 'components' => [
  2. 'db' => [
  3. 'class' => 'yii\db\Connection',
  4. 'dsn' => 'mysql:host=localhost;dbname=yiidemo',
  5. 'username' => 'root',
  6. 'password' => 'root',
  7. 'charset' => 'utf8',
  8. ],
  9. 'mailer' => [
  10. 'class' => 'yii\swiftmailer\Mailer',
  11. 'viewPath' => '@common/mail',
  12. // send all mails to a file by default. You have to set
  13. // 'useFileTransport' to false and configure a transport
  14. // for the mailer to send real emails.
  15. 'useFileTransport' => true,
  16. 'transport' => [
  17. 'class' => 'Swift_SmtpTransport',
  18. 'host' => 'smtp.qq.com',
  19. 'username' => '********@qq.com',
  20. 'password' => '********',
  21. 'port' => '465',
  22. 'encryption' => 'ssl',
  23. ],
  24. ],
  25. ],

控制器代码:

  1. public $modelClass = 'common\models\User';
  2. public function actions()
  3. {
  4. $actions = parent::actions();
  5. // 禁用"create" 操作后可用自己在控制器中写的方法
  6. unset($actions['update'],$actions['create'],$actions['delete']);
  7. //$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
  8. return $actions;
  9. }
  10. public function actionCreate(){
  11. $request = Yii::$app->request;
  12. $params = $request->post();
  13. if($params){
  14. $fromName = $request->getBodyParam('fromName');
  15. $fromBady = $request->getBodyParam('fromBady');
  16. $toName = $request->getBodyParam('toName');
  17. $body = $request->getBodyParam('body');
  18. return $this->send($fromName,$fromBady,$toName,$body);
  19. }
  20. return false;
  21. }
  22. /*
  23. * Email Send function
  24. * @param1 $fromName
  25. * @param1 $toName
  26. * @param1 $body
  27. * $return boo1ean
  28. *
  29. */
  30. public function send($fromName,$fromBady,$toName,$body = ''){
  31. $mail = \Yii::$app->mailer->compose()
  32. ->setFrom([$fromName=>$fromBady])
  33. ->setTo($toName)
  34. ->setSubject('邮件发送配置')
  35. ->setTextBody($body) //发布纯文字文本
  36. ->send();
  37. if($mail){
  38. return [
  39. 'name' => [
  40. 'fromName' => $fromName,
  41. 'fromBady' => $fromBady,
  42. 'toName' => $toName,
  43. 'body' => $body,
  44. ],
  45. 'message' => '发生到['.$toName.']的邮件成功!',
  46. 'code' => 0,
  47. 'status' => 200,
  48. ];
  49. }else{
  50. return [
  51. 'name' => 'Error',
  52. 'message' => '发生到'.$toName.'的邮件失败!',
  53. 'code' => 0,
  54. 'status' => 402,
  55. ];
  56. }
  57. }

但是你会发现数据返回是成功的但是你却没收到邮件

这是你应该把
'useFileTransport' => true 改成 'useFileTransport' => false,
并且你的邮箱密码是qq授权码(到你邮箱中的设置->账户 查看)

通过以上努力你会成功接收邮件!

以上就是Yii2邮件发送出现问题怎么解决的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行