#!/usr/bin/env python #coding: utf-8 by guozheng_li #该脚本加入了文本、图片以及附件功能,日常运维跑的脚本基本也就这三样够用了。可以发送给多人,只要添加相应的mailto_list即可,再加入该说明前验证是正常的 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage mailto_list=[‘745292907@qq.com‘,‘guozheng_li@quantone.com‘] mail_host="smtp.163.com" #设置服务器 mail_user="XXX" #用户名 mail_pass="XXXXXX" #口令 mail_postfix="163.com" #发件箱的后缀 def send_mail(to_list,sub): def addimg(src,imgid): fp = open(src, ‘rb‘) msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header(‘Content-ID‘, imgid) return msgImage msg = MIMEMultipart(‘related‘) msgtext = MIMEText(""" <table width="600" border="0" cellspacing="0" cellpadding="4"> <tr bgcolor="#CECFAD" height="20" style="font-size:14px"> <td colspan=2>*官网性能数据 <a href="monitor.domain.com">更多>></a></td> </tr> <tr bgcolor="#EFEBDE" height="100" style="font-size:13px"> <td> <img src="cid:io"></td><td> <img src="cid:key_hit"></td> </tr> <tr bgcolor="#EFEBDE" height="100" style="font-size:13px"> <td> <img src="cid:men"></td><td> <img src="cid:swap"></td> </tr> </table>""","html","utf-8") msg.attach(msgtext) msg.attach(addimg("a.png","io")) msg.attach(addimg("a.png","key_hit")) msg.attach(addimg("a.png","men")) msg.attach(addimg("a.png","swap")) #添加附件的地方,attach 三条少一不可,缺少最后一条将会发送一串码而不是真正附件。 attach = MIMEText(open("aa.xlsx", "rb").read(), "base64", "utf-8") attach["Content-Type"] = "application/octet-stream" attach["Content-Disposition"] = "attachment; filename=\"业务服务质量周报(12周).xlsx\"".decode("utf-8").encode("gb18030") msg.attach(attach) me="163"+"<"+mail_user+"@"+mail_postfix+">" msg[‘Subject‘] = sub msg[‘From‘] = me msg[‘To‘] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user,mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False if __name__ == ‘__main__‘: if send_mail(mailto_list,"hello"): print "发送成功" else: print "发送失败"
本文出自 “向往|那一片天空” 博客,请务必保留此出处http://fiyaster.blog.51cto.com/6668127/1676255
原文地址:http://fiyaster.blog.51cto.com/6668127/1676255