Zabbix 使用之利用Python发送HTML格式告警邮件

最早使用mail程序发送富文本的告警邮件,比较简单。

1
2
3
4
5
6
#!/bin/bash
export LANG=zh_CN.UTF-8
file=/tmp/zabbix_mail.txt
echo "$3" >$file
/usr/bin/dos2unix -k $file
/usr/bin/mail -s "$2" $1 <$file

现在使用python脚本格式化下邮件,多了一些告警参数,也更美观。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author : yeadoc
# Date : 2018/10/30
# Filename : SendMail.py

import sys
import smtplib
from email.mime.text import MIMEText

class Mail():
def __init__(self):
self.host = 'smtp.139.com'
self.port = '465'
self.user = 'XXX@139.com'
self.password = '邮箱密码'

def SendMail(self,to_addr,subject,message):
from_addr = self.user
msg = MIMEText(message,"html","utf-8")
msg["From"] = from_addr
msg["To"] = to_addr
msg["Subject"] = subject

try:
server = smtplib.SMTP_SSL()
server.set_debuglevel(1)
server.connect(self.host, self.port)
server.login(self.user,self.password)
server.sendmail(from_addr,to_addr,msg.as_string())
server.quit()
except smtplib.SMTPException:
print "Error: Email can't send!"

if __name__ == '__main__':
zabbix = Mail()
zabbix.SendMail(sys.argv[1],sys.argv[2],sys.argv[3])

Zabbix 创建媒体类型

点选Administration->Media types,创建一新脚本媒体类型

配置Zabbix用户邮箱

点选Administration->Users,选择管理员用户

在用户管理界面,选择Media选项

配置Zabbix 动作

点选Configuration->Actions,创建一个动作

配置告警主题及内容

告警内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SendMail HTML 代码</title>
</head>
<body>
<table border="1" width="100%">
<tr>
<td style="width: 35%">告警时间</td>
<td style="width: 65%">{EVENT.DATE} {EVENT.TIME}</td>
</tr>
<tr>
<td>告警主机</td>
<td bgcolor="#FF3333">{HOST.NAME}</td>
</tr>
<tr>
<td>告警等级</td>
<td>{TRIGGER.SEVERITY}</td>
</tr>
<tr>
<td>告警信息</td>
<td>{TRIGGER.NAME}</td>
</tr>
<tr>
<td>告警项目</td>
<td>{TRIGGER.KEY1}</td>
</tr>
<tr>
<td>问题详情</td>
<td>{ITEM.NAME}:{ITEM.VALUE}</td>
</tr>
<tr>
<td>当前状态</td>
<td>{TRIGGER.STATUS}:{ITEM.VALUE1}</td>
</tr>
<tr>
<td>事件ID</td>
<td>{EVENT.ID}</td>
</tr>
</table>
</body>
</html>

恢复内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SendMail HTML 代码</title>
</head>
<body>
<table border="1" width="100%">
<tr>
<td style="width: 35%">恢复时间</td>
<td style="width: 65%">{EVENT.DATE} {EVENT.TIME}</td>
</tr>
<tr>
<td>恢复主机</td>
<td bgcolor="#7fff00">{HOST.NAME}</td>
</tr>
<tr>
<td>告警等级</td>
<td>{TRIGGER.SEVERITY}</td>
</tr>
<tr>
<td>告警信息</td>
<td>{TRIGGER.NAME}</td>
</tr>
<tr>
<td>告警项目</td>
<td>{TRIGGER.KEY1}</td>
</tr>
<tr>
<td>问题详情</td>
<td>{ITEM.NAME}:{ITEM.VALUE}</td>
</tr>
<tr>
<td>当前状态</td>
<td>{TRIGGER.STATUS}:{ITEM.VALUE1}</td>
</tr>
<tr>
<td>事件ID</td>
<td>{EVENT.ID}</td>
</tr>
</table>
</body>
</html>

告警效果

一分、两分都是爱!