标签:add tle 文件 else info hello smtp 代码 pyhton
Python使用smtplib和email库发送邮件,发送HTML格式正文,插入图片,以及发送execl等文件。实例代码如下:#/usr/bin/env python
#-*- coding:utf-8 -*-
#auther:yuanmuc
#email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
from email.mime.application import MIMEApplication
import time
#收件人列表
mailto_list = [‘yuan@163.com‘,‘liu@123.com‘]
#发件人用户名
mail_user = "monitor"
#邮件域后缀
mail_postfix = "localtest"
def Send_Mail(to_list,sendinfo):
#邮件标题
title = "网络质量告警" + time.strftime(‘%Y%m%d‘,time.localtime(time.time()))
#增加图片附件
def addimg(src,imgid):
fd = open(src,‘rb‘)
msgImage = MIMEImage(fd.read())
fd.close()
msgImage.add_header("Content-ID",imgid)
return msgImage
#发送execl附件
def attachexecl(f):
part = MIMEApplication(open(f,‘rb‘).read())
part.add_header("Content-Disposition",‘attachment‘,filename=f)
msg.attach(part)
msg = MIMEMultipart(‘related‘)
#html邮件正文
msgtext = MIMEText(sendinfo,"html","utf-8")
msg.attach(msgtext)
#添加图片,imgid是html中的图片id
imgfile = "a.png"
imgid = "hello"
msg.attach(addimg(imgfile,imgid))
#添加execl附件
execlfile = "test.xlsx"
attachexecl(execlfile)
#连接邮件服务器
me = mail_user + "@" + mail_postfix
msg["Subject"] = title
msg["From"] = me
msg["To"] = ";".join(to_list)
send_to = to_list
try:
server = smtplib.SMTP("192.168.1.192")
server.set_debuglevel(1)
server.sendmail(me,send_to,msg.as_string())
return True
except Exception e:
print str(e)
def Main(sendinfo):
if Send_Mail(mailto_list,sendinfo):
print "发送成功"
else:
print "发送失败"
if __name__ == ‘__main__‘:
sendhtml = "<h1>这是一个测试</h1><img src="cid:hello" width=‘650‘ height=‘220‘/>"
Main(sendhtml)
标签:add tle 文件 else info hello smtp 代码 pyhton
原文地址:http://blog.51cto.com/12824426/2174478