#coding:utf-8 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage HOST="smtp.126.com" SUBJECT=u"测试带图附件邮件" TO="***@foxmail.com" FROM='***@126.com' 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("<font color=red>测试发图:<br><img src=\"cid:weekly\" border=\"1\"><br></font>","html","utf-8") msg.attach(msgtext) msg.attach(addimg("C:/Users/Administrator/PycharmProjects/untitled\R13.png","weekly")) attach=MIMEText(open("C:/Users/Administrator/PycharmProjects/untitled/chart.xlsx","rb").read(),"base64","utf-8") attach["Content-Type"]="application/octet-stream" attach["Content-Disposition"]="attachment; filename=\"chart.xlsx\"".decode("utf-8").encode("gb18030") msg.attach(attach) msg['Subject']=SUBJECT msg['From']=FROM msg['To']=TO try: server=smtplib.SMTP() server.connect(HOST,'25') server.starttls() server.login("***@126.com","******") server.sendmail(FROM,TO,msg.as_string()) server.quit() print "邮件发送成功!" except Exception,e: print "失败:"+str(e)