前言:继前篇zabbix邮件乱码问题解决,转码后,问题是解决了,但是又发现问题,有时候告警邮件没有邮件内容,只有标题,一直没找出原因,所以就换了Python脚本发送邮件,代码如下。
使用前当然是要先安装python了,然后是导入相关的运行库smtplib,python的smtplib提供了一种很方便的途径发送电子邮件,它对smtp协议进行了简单的封装。
#!/usr/bin/python #coding:utf-8 import smtplib from email.mime.text import MIMEText import sys # configure your own parameters here #下面邮件地址的smtp地址 mail_host = 'smtp.mail.qq.com' #用来发邮件的邮箱,在发件人抬头显示(不然你的邮件会被当成是垃圾邮件) mail_user = 'XXXX@qq.com' #上面邮箱的密码 mail_pass = 'XXXX!' #上面smtp地址的主网站地址 mail_postfix = 'mail.qq.com' def send_mail(to_list,subject,content): me = mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content, 'plain', 'utf-8') # 必须使用'utf-8'参数,否则默认为us-ascii, 在部分邮件客户端中文会显示为乱码 msg['Subject'] = subject msg['From'] = me msg['to'] = to_list try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me,to_list,msg.as_string()) s.close() return True except Exception,e: print str(e) return False if __name__ == "__main__": send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
脚本主要就改4项:
#下面邮件地址的smtp地址
mail_host = 'smtp.mail.qq.com'
#用来发邮件的邮箱,在发件人抬头显示(不然你的邮件会被当成是垃圾邮件)
mail_user = 'XXX@qq.com'
#上面邮箱的密码
mail_pass = 'XXXXX'
#上面smtp地址的主网站地址
mail_postfix = 'mail.qq.com'
这个脚本需要输入三个参数来测试:
第一个是要发送的邮件地址,
第二个是邮件标题,
第三个是邮件内容
python sendmail.py XXXX@qq.com title 'content'
收到邮件就完成了.
发送邮件改进:
支持发送多人,支持发送附件,代码如下:
#!/usr/bin/python #coding:utf-8 # import smtplib import sys from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.mime.text import MIMEText #配置你的邮箱信息 mail_host = 'smtp.mail.qq.com' mail_user = 'XXXX@qq.com' mail_pass = 'XXXX' mail_postfix = 'mail.qq.com' #发送邮件函数 def send_mail(to_list,subject,content,file_list): #采用related定义内嵌资源的邮件体 msg = MIMEMultipart('related') #邮件内容 msgtext = MIMEText(content, 'plain', 'utf-8') msg.attach(msgtext) #附件部分 for attachfile in file_list.split(','): attach = MIMEApplication(open(attachfile,'rb').read()) attach.add_header('Content-Disposition', 'attachment', filename=attachfile) msg.attach(attach) me = mail_user+"<"+mail_user+"@"+mail_postfix+">" msg['Subject'] = subject msg['From'] = me mail_to_list = to_list.split(',') msg['to'] = ','.join(mail_to_list) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me,mail_to_list,msg.as_string()) s.close() return True except Exception,e: print "发送失败"+str(e) return False if __name__ == "__main__": send_mail(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
用法:
./sendmail.mult.py "xxxxxx@qq.com,xxxxx@163.com" "title_test" "content1234" "attachfile1,attachfile2"
说明:多个邮箱用逗号隔开,多个附件用邮件隔开。
还可以实现抄送和密送,上述脚本可把配置项放入配置文件,后期有时间再优化调整。
来源:https://www.cnblogs.com/jjzd/p/6617499.html