从zabbix获取的监控数据和图形通过python脚本发送邮件

发布时间 2024-01-03 14:02:55作者: 随心朝阳

1.直接上python脚本(python版本为 2.7)

#coding:utf8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import time
import os

#邮件内容可以执行脚本或者自定义信息内容(这里的脚本可以是从zabbix获取的监控数值)
#result = os.popen("/root/script/result_id.sh")
#read = result.read()
read = "asdadada"

localtime = time.strftime("%Y%m%d", time.localtime())
print "本地时间为 :", localtime
sender = 'xxxxxxxxx@163.com'   #发送人邮箱
passwd = 'xxxxxxxxxxxxx' #发送人邮箱授权码
#receivers = ['xxxxxxxxxxxx1@163.com','xxxxxxxxxxxx2@163.com','xxxxxxxxxxxx3@163.com'] #收件人邮箱
receivers = ['test@qq.com'] #自己的邮箱
subject = 'xxxxxxxxx时段统计图形展示' #主题
#content = '这是我使用python smtplib模块和email模块自动发送的邮件'    #正文

msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['TO'] = ",".join(receivers)
msg['Subject'] = Header(subject, 'utf-8')
msg.attach(MIMEText(read,'plain','utf-8'))

#att1可以有多个,直接复制即可
att1 = MIMEText(open('/root/script/%s_iptables_config.png'%(localtime), 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename=%s_iptables_config.jpg'%(localtime)
msg.attach(att1)

#我这里用的163邮箱,其他邮箱自行百度
try:
    s = smtplib.SMTP_SSL('smtphz.qiye.163.com',465)
    s.login(sender,passwd)
    s.sendmail(sender,receivers,msg.as_string())
    print('发送成功')

except Exception,e:
    print e

 2.验证邮件是否正确