grafana使用邮箱发告警接口脚本

1.先在邮箱获取密码,qq或者163都可以在那个smtp那边页面获取或者设置。
2.后台运行下面脚本。
3.grafana添加告警通道,设置告警。

# !/usr/bin/env python
# _*_ coding: utf-8 _*_

from flask import Flask, request
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
app = Flask(__name__)

@app.route("/send_mail", methods=["POST"])
def send_mail():
    info = request.json
    print("#########:",info, type(info))
    cusname = "随便自定义"
    alter_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    state = info['state']
    ruleName = info['ruleName']
    title=info['title']
    #message=info['message']
    metric=[]
    value=[]
    for i in range(0, len(info['evalMatches'])):
        metric.append(info['evalMatches'][i]['metric'])
        value.append(info['evalMatches'][i]['value'])
    content = """
    商户: %s
    主机: %s
    级别: %s
    规则: %s
    报警值: %s
    时间: %s
    """ % (cusname,metric,state,ruleName,value,alter_time)
    print(content)
    mail_sever = 'smtp.qq.com'
    mail_user = '你的邮箱'
    mail_pass = '你的密码'
    sender = '你发邮件的邮箱'
    reciver = '你接收的邮箱'
    msg = MIMEText(content, "plain", 'utf-8')
    msg['Subject'] = title
    msg['From'] = sender
    msg['To'] = reciver
    smtp = smtplib.SMTP()
    smtp.connect(mail_sever)
    smtp.login(user=mail_user, password=mail_pass)
    smtp.sendmail(sender, reciver, msg.as_string())
    return "成功"

if __name__ == "__main__":
    app.run("0.0.0.0", "5000")

你可能感兴趣的:(python,flask,grafana,email)