博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
发送带有正文以及附件的邮件
阅读量:4946 次
发布时间:2019-06-11

本文共 1817 字,大约阅读时间需要 6 分钟。

为什么要写下了呢? 因为本人找了好久,网上都是 “发送带有正文的邮件”或者“发送带有附件的邮件”。就没见到一篇是“发送带有正文+附件的邮件”。导致本人折腾这个折腾了好久,太浪费时间了。写下来留作后续参考。

下面是在邮件里面,正文显示 a.html内容,并且附件附上a.html。

 

# coding: utf-8import smtplibfrom email.header import Headerfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom os.path import basenamedef send_report():    smtpserver = "smtp.xx.com"    user = "user1"    sender = "user1@xx.com"    password = "pw1"    receivers = "user1@xx.com;user2@xx.com"#     receivers_list = ['user1@xx.com','user2@xx.com']#     receivers=";".join(receivers_list)    mail_subject='Send Email Test'    send_file="a.html"        send_mail(smtpserver, user, password, sender, receivers, mail_subject,send_file,send_file)        print('Email has send out successfully!')    def send_mail(smtpserver,user,password,sender,receivers,m_subject,m_content,m_attachment):        msg=MIMEMultipart('alternative')    msg['Subject']=Header(m_subject,'utf-8')    msg['From']=sender    msg['To']=receivers        #mail content    with open(m_content,"rb") as f:        mail_content=f.read()    msg.attach(MIMEText(mail_content,'html','utf-8'))        #mail attachment    with open(m_attachment,"rb") as f:        mail_attach=f.read()    send_attachment=MIMEText(mail_attach,'html','utf-8')    send_attachment["Content-Type"]='application/octet-stream'    send_attachment["Content-Disposition"]='attachment;filename='+basename(m_attachment)    msg.attach(send_attachment)        try:        smtp=smtplib.SMTP()        smtp.connect(smtpserver)        smtp.login(user, password)        smtp.sendmail(sender,receivers.split(";"),msg.as_string())        smtp.quit()    except Exception as e:        print("Send Email Failed!!!")        raise e    if __name__ == "__main__":    send_report()

 

转载于:https://www.cnblogs.com/miniren/p/5368844.html

你可能感兴趣的文章
判断一个数是否是2^N次方
查看>>
打印图形
查看>>
ngx_http_core_module 模块
查看>>
两个常见的oracle索引
查看>>
实验十 指针2
查看>>
[python]pickle和cPickle
查看>>
剑指Offer--二叉树的镜像
查看>>
PAT-BASIC-1031-查验身份证
查看>>
连连看小游戏
查看>>
(180905)如何通过梯度下降法降低损失----Google机器学习速成课程笔记
查看>>
面试介绍项目经验(转)
查看>>
<metro>Google的验证
查看>>
Oracle 表的分组操作
查看>>
在OS X上的Intllij Idea中配置GlassFish
查看>>
用查表法快速转换yv12到RGB【转】
查看>>
使用公钥登录SSL
查看>>
hdu 1290_献给杭电五十周年校庆的礼物
查看>>
豆瓣电影api
查看>>
BufferedInputStream和FileInputStream的区别
查看>>
likely() 和 unlikely()
查看>>