昊天SEO

【Python】发送带文字图片附件的邮件

  • smtplib模块负责连接服务器和发送邮件
  • MIMEAudio:定义邮件的音频数据
  • MIMEImage:定义邮件的图片数据
  • MIMEText:定义邮件的文字数据
  • MIMEMultipart:负责将文字图片音频组装在一起和添加附件

#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

HOST = “smtp.gmail.com”
SUBJECT = u”官网业务服务质量周报”
TO = “test@qq.com”
FROM = “test@gmail.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(“img/weekly.png”,”weekly”))

attach = MIMEText(open(“doc/week_report.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)

msg[‘Subject’] = SUBJECT
msg[‘From’]=FROM
msg[‘To’]=TO
try:
server = smtplib.SMTP()
server.connect(HOST,”25”)
server.starttls()
server.login(“test@gmail.com”,”123456″)
server.sendmail(FROM, TO, msg.as_string())
server.quit()
print “邮件发送成功!”
except Exception, e:
print “失败:”+str(e)

网站的维护离不开大家的支持鼓励,捐赠让我更有动力走的更远&& 也可以关注我的微信公众号,发布更多的干货
本文网址:https://www.168seo.cn/python/2174.html

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址