使用Python通过SMTP发送邮件
2019-08-14 14:53 williamzheng 阅读(542) 评论(0) 编辑 收藏 举报有些业务可能由于各种各样的原因并不适用于Zabbix监控,这时如果要做到系统出问题能立即发送邮件,就需要自己来写监控脚本了,出问题要实时通过邮件报警,以下案例使用Python脚本实现通过SMTP协议发送邮件,一般可用于自定义报警
Python代码
方案一
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import sys,os,string,time,datetime,re
from sys import stdout
import poplib
import smtplib
from email.header import decode_header
from email.mime.text import MIMEText
import email
def send_mail(sender, receiver,strsubject,strcontent):
_user = "xxx@163.com"
_pwd = "xxx"
sent =smtplib.SMTP_SSL('smtp.163.com',465)
sent.login(_user, _pwd)
to = receiver.split(";")
content=MIMEText(strcontent,'html',_charset='UTF-8')
content['Subject']=strsubject
content['From']=sender
content['To']=','.join(to)
sent.sendmail('xxx@163.com',to,content.as_string())
sent.close()
## main ##
if __name__=='__main__':
## get the path in the config file
if len(sys.argv) != 4:
print "sender,receiver,subject"
sys.exit(1)
sender=sys.argv[1]
receiver=sys.argv[2]
subject=sys.argv[3]
content =sys.stdin.read()
send_mail(sender, receiver, subject, content);
方案二
#!/usr/bin/python
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
from sys import argv
mailto_list=[]
mail_host="smtp.163.com:25" #设置服务器
mail_user="xxx@163.com" #发件用户名(换成自己的)
mail_pass="xxx" #口令(换成自己的)
#mail_postfix="163.com" #发件箱的后缀
debug_level=0 #是否开启debug
def send_mail(to_list,sub,content):
me=mail_user
msg = MIMEText(content,_subtype='plain',_charset='utf-8')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.set_debuglevel(debug_level)
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception as e:
print('except:',e)
return False
if __name__ == '__main__':
try:
mailto_list=argv[1].split(';')
sub=argv[2]
content=argv[3]
except:
print("python send_mail.py 'user1@xx.com;user2@xx.com' sub content")
exit()
if send_mail(mailto_list,sub,content):
print("发送成功")
else:
print("发送失败")
WilliamZheng©版权所有 转载请注明出处! 觉得对您有帮助请点个赞哟~ 运维架构师群:833329925