一、Python发送邮件
import smtplib from email.mime.text import MIMEText def send(email_to,title,content): msg = MIMEText(content,"plain","utf-8") froms = "1257063655@qq.com" to_list = email_to.replace("\n","").split(",") print(to_list) msg["Subject"] = title # 传参 msg["From"] = froms # 发件人 msg["To"] = email_to # 收件人 server = smtplib.SMTP_SSL("smtp.qq.com",465) server.login(froms,"oylltctlxijogdbb") server.sendmail(froms,to_list,msg.as_string()) # 发送人,收件人列表, # 内容 print("发送成功") server.quit() title = "邮件报警测试" content = """系统磁盘空间或内存可能快要满了""" email_to = """ 1257063655@qq.com """ if __name__ == '__main__': send(email_to,title,content)
二、zabbix实现邮件报警
1)添加python脚本文件
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import smtplib import sys from email.mime.text import MIMEText def send_mail(email_to,title,content): msg = MIMEText(content,"plain","utf-8") froms = "1257063655@qq.com" to_list = email_to.replace("\n","").split(",") print(to_list) msg["Subject"] = title # 传参 msg["From"] = froms # 发件人 msg["To"] = email_to # 收件人 server = smtplib.SMTP_SSL("smtp.qq.com",465) server.login(froms,"oylltctlxijogdbb") server.sendmail(froms,to_list,msg.as_string()) server.quit() if __name__ == '__main__': send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
2) 使用shell脚本去调用python脚本来进行发送邮件
[root@zabbix alertscripts]# cat send_email.sh #!/bin/sh /usr/bin/python3 /usr/local/zabbix/alertscripts/send_email.py $1 $2 $3
[root@zabbix alertscripts]# chmod o+x send_email.sh
163邮箱测试
from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import logging import smtplib def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) from_addr = 'nick1236xx@163.com' password = 'dasb1234' # 授权码 # 输入SMTP服务器地址: smtp_server = 'smtp.163.com' def sendmail(to_addr, link, secure=True): title = '<html><body><h3>亲爱的<a data-auto-link="1" href="mailto:%s" target="_blank">%s</a>,您好:</h3>' % (to_addr, to_addr) reset = "<div style = 'padding-left:55px;padding-right:55px;font-family:'微软雅黑','黑体',arial;font-size:14px;'>重置密码</div>" body = '<p>请点击以下链接进行重置密码 <a href="%s">%s</a></p>' % (link, reset) tail = '如果您并不是Awesome用户,可能是其他用户误输入了您的邮箱地址。</body></html>' html = title + body + tail msg = MIMEText(html, 'html', 'utf-8') # 发送地址格式 都需要编码 msg['From'] = _format_addr('Awesome Python Webapp <%s>' % from_addr) msg['To'] = _format_addr('亲爱的用户 <%s>' % to_addr) msg['Subject'] = Header('重置密码', 'utf-8').encode() try: if secure: server = smtplib.SMTP_SSL(smtp_server, 465) # 启用SSL发信, 端口一般是465 else: server = smtplib.SMTP(smtp_server, 25) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit() except smtplib.SMTPException as e: logging.error('sendemail:%s' % e) if __name__ == '__main__': # 输入收件人地址: to_addr = '150648003@qq.com' sendmail(to_addr, 'http://www.baidu.com', True)