第一步修改配置文件:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.exmail.qq.com
MAIL_PORT=465
MAIL_USERNAME=邮箱地址
MAIL_PASSWORD=邮箱授权码
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=邮箱地址
MAIL_FROM_NAME=邮箱名称(自己定义)

这里使用的是腾讯企业邮箱的smtp驱动,可根据实际情况来更改

第二步生成邮件类,所有的邮寄类配置都在 build 方法中完成,可以调用from,subject, view, 和 attach 来配置邮件的内容和发送

php artisan make:mail AlarmsMail

第三步,编辑邮件类

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class AlarmsMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    private $err;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($e)
    {
        $data = [
            'msg'  => $e->getMessage(),
            'code' => $e->getCode(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
        ];

        $this->err     = $data;
        $this->subject = "XXXX告警";
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('mail.alarms', $this->err);
    }
}

第四步,创建视图

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<head>
    <style>
        .list-group {
            padding-left: 0;
            margin-bottom: 20px;
        }

        .list-group-item {
            position: relative;
            display: block;
            padding: 10px 15px;
            margin-bottom: -1px;
            background-color: #fff;
            border: 1px solid #ddd;
        }

        .code {
            color: red;
        }

        .col-md-12 {
            width: 100%;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="list-group">
                <span class="list-group-item code">错误码:{{$code}}</span>
                <span class="list-group-item code">错误内容:{{$msg}}</span>
                <span class="list-group-item code">错误文件:{{$file}}</span>
                <span class="list-group-item code">错误行数:{{$line}}</span>
            </div>
        </div>
    </div>
</div>
</body>
</html>

第五步,调用

use Illuminate\Support\Facades\Mail;
use App\Mail\AlarmsMail;

try {
            throw new \Exception("我是一个异常,我异常了");
        } catch (\Exception $e){
            Mail::to(config('services.alarms_receive_mail'))->send(new AlarmsMail($e));
        }

结果:
image.png

至此一个简单版的异常告警邮件发送已经完成了,还有好多的配置可以操作,比如发送纯文本邮件,增加附件,还可以抄送和密送收件人,具体可以参考文档 https://learnku.com/docs/lara...


LinAt
10 声望0 粉丝