python3发送html格式的邮件

时间:2023-12-12 09:24:50
def send_mail(to_list, sub, content, attpath):
me = "*******" + "<" + mail_user + "@" + mail_postfix + ">"
msg = MIMEMultipart()
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list) htmlf=open(attpath,'r',encoding="utf-8")
htmlcont=htmlf.read() email_text = MIMEText(htmlcont, _subtype='html')
msg.attach(email_text)
sep = os.sep
attname = attpath.split(sep)[-]
# 首先是xlsx类型的附件
email_att = MIMEApplication(open(attpath, 'rb').read())
email_att.add_header('Content-Disposition', 'attachment', filename=attname)
msg.attach(email_att)
try:
server = smtplib.SMTP()
server.connect(mail_host) # 连接服务器
server.login(mail_user, mail_pass) # 登录操作
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except BaseException:
return False

关键是加入

_subtype='html',如果是普通文本,就是plain,