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

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

return [
    'components' => [
        /** 邮件配置 **/
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'useFileTransport' =>false,//这句一定有,false发送邮件,true只是生成邮件在runtime文件夹下,不发邮件
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.qq.com',  //每种邮箱的host配置不一样
                'username' => 'tinymeng@qq.com',
                'password' => '*****邮箱授权码****',
                'port' => 465,
                'encryption' => 'ssl',
            ],
            'messageConfig'=>[
                'charset'=>'UTF-8',
                'from'=>['tinymeng@qq.com'=>'tinymeng网络科技管理员']
            ],
        ],
        /** 获取异常并发送邮件 */
         'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\EmailTarget',
                    'levels' => ['error'],//['error', 'warning']
                    'mailer' => 'mailer',
                    'message' => [
                        'from' => ['tinymeng@qq.com'],
                        'to' => ['send@majiameng.com'],
                        'subject' => 'System find an error,Please handel it immediately',
                    ],
//                    'categories' => ['yii\db\*', 'yii\web\HttpException:*'], // 只处理数据库和请求导致的错误
                    'except' => ['yii\web\HttpException:404'],  // 排除404,不然的话你会发现你的邮箱里全塞满了这些邮件
                ],
            ],
        ],
    ]

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

$mail= \Yii::$app->mailer->compose();
$mail->setTo('tinymeng@qq.com');
$mail->setSubject("测试邮件");
//$mail->setTextBody('测试文本');   //发布纯文字文本
$mail->setHtmlBody("<br>你好");    //发布可以带html标签的文本
if($mail->send()){
    echo "success";
}else{
    echo "failse";
}
Last modification:September 23rd, 2019 at 04:23 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment