Python连载56-发送带有附件、正文为HTML的邮件
一、HTML格式怎么发送右键
1.准备HTML代码作为内容
2.把邮件的subtype设置为html
3.发送
4.举个例子:自己发给自己一个HTML格式的文件
from email.mime.text import MIMEText ? main_content = """ <!DOCTYPE html> <html lang = "en" <head> <meta charset = "UTF-8"> <title>实例</title> </head> <body> <h1>这个是做测试用的html<h1> </body> </html> """ ? msg = MIMEText(main_content,"html","utf-8") ? #构建发送者地址和登录信息 from_addr = "" from_pwd = "" #构建邮件接受者的信息 to_addr = "" smtp_srv = "smtp.qq.com" try: import smtplib srv = smtplib.SMTP_SSL(smtp_srv.encode(),465) srv.login(from_addr,from_pwd) srv.sendmail(from_addr,[to_addr],msg.as_string()) srv.quit() ? except Exception as a: print(a)
二、发送带附件的邮件
1.可以把邮件看作是一个文本邮件和一个附件的合体
2.一封邮件如果涉及多个部分,需要使用MIMEMultipart格式构建
3.添加一个MIMEText正文
4.添加一个 MIMEBase或者MEMEText作为附件
5.举个例子:
from email.mime.text import MIMEText#构建附件使用 from email.mime.multipart import MIMEBase,MIMEMultipart#构建基础邮件使用 ? mail_mul = MIMEMultipart()#构建一个邮件对象 mail_text = MIMEText("Hello,I am liudana","plain","utf-8")#构建邮件正文 mail_mul.attach(mail_text)#把构建好的邮件正文附加到邮件中 #构建附件,需要从本地读入附件 #打开一个本地文件 #以rb格式打开 with open("00.TestCasePython.py","rb") as f: s = f.read() #设置附件的MIME和文件名 m = MIMEText(s,"base64","utf-8")#类型是base64,这是邮件正文的格式,这里只需要记住就可以了 m["Content-Type"] = "application/octet-stream" #需要注意 #1.attachment后分号位英文状态 #2.filename后面需要引号包裹,注意与外面引号错开 m["Content-Disposition"] = "attachment;filename = ‘00.TestCasePython.py‘" #添加到MIMEMultipart mail_mul.attach(m) ? #构建发送者地址和登录信息 from_addr = "" from_pwd = "ysqmojzwkgfciccd" #构建邮件接受者的信息 to_addr = "" smtp_srv = "smtp.qq.com" try: import smtplib srv = smtplib.SMTP_SSL(smtp_srv.encode(),465) srv.login(from_addr,from_pwd) srv.sendmail(from_addr,[to_addr],mail_mul.as_string()) srv.quit() ? except Exception as a: print(a)
三、源码
D55_2_HTMLMailSend.py
D55_3_SendAttachmentMail.py
https://github.com/ruigege66/Python_learning/blob/master/D55_2_HTMLMailSend.py
https://github.com/ruigege66/Python_learning/blob/master/D55_3_SendAttachmentMail.py
2.CSDN:https://blog.csdn.net/weixin_44630050
3.博客园:https://www.cnblogs.com/ruigege0000/
4.欢迎关注微信公众号:傅里叶变换,个人公众号,仅用于学习交流,后台回复”礼包“,获取大数据学习资料
相关推荐
shipinsky 2020-09-23
zhangwentaohh 2020-09-16
文山羊 2020-08-16
心丨悦 2020-08-03
Dukezhao 2020-07-04
xiaodaiwang 2020-06-12
zk0 2020-06-07
我欲疾风前行 2020-06-04
mxcsdn 2020-05-27
yznkaixin 2020-05-14
千锋 2020-05-13
Sophisticated 2020-05-09
老和山下的小学童 2020-05-11
llwang0 2020-05-06
小灰笔记 2020-03-16
vs00ASPNET 2020-02-19
86206132 2020-01-09
atb 2019-12-27