参考一下
[Python] 纯文本查看 复制代码 def fill_text(self):
# 邮件头信息
self.msg_root['From'] = Header(self.email_from)
# self.msg_root['To'] = Header(','.join(self.email_to)) # 如果为列表
self.msg_root['To'] = Header(self.email_to) # 单个邮箱
self.msg_root['Subject'] = Header(self.subject, 'utf-8')
# 邮箱正文内容,第一个参数为内容,第二个参数为格式(plain 为纯文本;html 网页),第三个参数为编码
text_sub = MIMEText(self.text_info, 'plain', 'utf-8')
self.msg_root.attach(text_sub)
# 构造超文本内容
# html_sub = MIMEText(self.html_info, 'html', 'utf-8')
# # 如果不加下边这行代码的话,上边的文本是不会正常显示的,会把超文本的内容当做文本显示
# html_sub["Content-Disposition"] = 'attachment; filename="csdn.html"'
# self.msg_root.attach(html_sub)
if self.file_info:
# 构造附件
for i in self.file_info:
file_sub = open(i, 'rb').read()
txt = MIMEText(file_sub, 'base64', 'utf-8')
txt["Content-Type"] = 'application/octet-stream'
# 以下代码可以重命名附件为hello_world.txt
filename = i.split('\\')[-1]
txt.add_header('Content-Disposition', 'attachment', filename=filename)
self.msg_root.attach(txt)
def send_email(self):
# 开启发信服务,这里使用的是加密传输
server = smtplib.SMTP_SSL(self.smtp_server)
server.connect(self.smtp_server, 465)
# 登录发信邮箱
server.login(self.email_from, self.email_psw)
# 发送邮件
server.sendmail(self.email_from, self.email_to, self.msg_root.as_string())
# 关闭服务器
server.quit() |