您现在的位置是:首页 > 文章详情

Python-SMTP发送邮件(HTML、图片、附件)

日期:2018-06-08点击:411

前言:

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。


一、Python发送HTML邮件

# -*- coding: utf-8 -*- # @Time : 2018/6/6 上午11:27 # @Author : Wang # @File : test_mail_html.py import smtplib from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def sendMail(): # 定义相关数据,请更换自己的真实数据 smtpserver = 'smtp.163.com' sender = 'test1@163.com' #receiver可设置多个,使用“,”分隔 receiver = 'wang@mobile.cn,zhang@mobile.cn,lily@mobile.cn' username = 'test1@163.com' password = '2018' msg = MIMEMultipart() boby = """ <h3>Hi,all</h3> <p>附件为本次FM_自动化测试报告。</p> <p>请解压zip,并使用Firefox打开index.html查看本次自动化测试报告结果。</p> """ mail_body = MIMEText(boby, _subtype='html', _charset='utf-8') msg['Subject'] = Header("Android_自动化测试报告", 'utf-8') msg['From'] = sender receivers = receiver toclause = receivers.split(',') msg['To'] = ",".join(toclause) print(msg['To']) msg.attach(mail_body) # 登陆并发送邮件 try: smtp = smtplib.SMTP() ##打开调试模式 # smtp.set_debuglevel(1) smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, toclause, msg.as_string()) except: print("邮件发送失败!!") else: print("邮件发送成功") finally: smtp.quit()

二、Python发送邮件带附件

#添加report附件 att = MIMEText(open("/report/html.zip", "rb").read(), "base64", "utf-8") att["Content-Type"] = "application/octet-stream" times = time.strftime("%m_%d_%H_%M", time.localtime(time.time())) filename_report = 'FM_Android_Report'+'_'+times+'.zip' att["Content-Disposition"] = 'attachment; filename= %s ' %filename_report msg.attach(att)

三、Python发送邮件正文带图片

msg = MIMEMultipart() boby = """ <h3>Hi,all</h3> <p>附件为本次FM_自动化测试报告。</p> <p>请解压zip,并使用Firefox打开index.html查看本次自动化测试报告结果。</p> <p> <br><img src="cid:image1"></br> </p> <p> """ msg.attach(mail_body) fp = open("/image/1.png", 'rb') images = MIMEImage(fp.read()) fp.close() images.add_header('Content-ID', '<image1>') msg.attach(images)

以上~~对你有帮助的话,点赞吧~

作者:搁浅
出处: http://www.cnblogs.com/xiaoxi-3-/
如果对您有帮助,请关注我的同名简书:https://www.jianshu.com/u/da1677475c27
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文链接:https://yq.aliyun.com/articles/630318
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章