您现在的位置是:首页 > 博客日记 > Php Php

yii2捕捉异常日志发送邮件通知

2019-09-17 17:43:13 【Php】 人已围观

修改配置文件common/config/main.php,在components中添加邮箱和日志配置

  1. return [
  2. 'components' => [
  3. /** 邮件配置 **/
  4. 'mailer' => [
  5. 'class' => 'yii\swiftmailer\Mailer',
  6. 'useFileTransport' =>false,//这句一定有,false发送邮件,true只是生成邮件在runtime文件夹下,不发邮件
  7. 'transport' => [
  8. 'class' => 'Swift_SmtpTransport',
  9. 'host' => 'smtp.qq.com', //每种邮箱的host配置不一样
  10. 'username' => 'tinymeng@qq.com',
  11. 'password' => '*****邮箱授权码****',
  12. 'port' => 465,
  13. 'encryption' => 'ssl',
  14. ],
  15. 'messageConfig'=>[
  16. 'charset'=>'UTF-8',
  17. 'from'=>['tinymeng@qq.com'=>'tinymeng网络科技管理员']
  18. ],
  19. ],
  20. /** 获取异常并发送邮件 */
  21. 'log' => [
  22. 'traceLevel' => YII_DEBUG ? 3 : 0,
  23. 'targets' => [
  24. [
  25. 'class' => 'yii\log\EmailTarget',
  26. 'levels' => ['error'],//['error', 'warning']
  27. 'mailer' => 'mailer',
  28. 'message' => [
  29. 'from' => ['tinymeng@qq.com'],
  30. 'to' => ['send@majiameng.com'],
  31. 'subject' => 'System find an error,Please handel it immediately',
  32. ],
  33. // 'categories' => ['yii\db\*', 'yii\web\HttpException:*'], // 只处理数据库和请求导致的错误
  34. 'except' => ['yii\web\HttpException:404'], // 排除404,不然的话你会发现你的邮箱里全塞满了这些邮件
  35. ],
  36. ],
  37. ],
  38. ]

如果在其他地方需要使用到邮件发送,具体代码如下

  1. $mail= \Yii::$app->mailer->compose();
  2. $mail->setTo('tinymeng@qq.com');
  3. $mail->setSubject("测试邮件");
  4. //$mail->setTextBody('测试文本'); //发布纯文字文本
  5. $mail->setHtmlBody("<br>你好"); //发布可以带html标签的文本
  6. if($mail->send()){
  7. echo "success";
  8. }else{
  9. echo "failse";
  10. }


关注TinyMeng博客,更多精彩分享,敬请期待!
 

很赞哦! ()