python3发送html格式的邮件

本文介绍了一种使用Python发送带有HTML格式内容和xlsx附件的电子邮件的方法。通过smtplib和email库,详细展示了如何设置邮件头部信息,读取HTML内容,以及添加附件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)[-1]
    # 首先是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,

转载于:https://www.cnblogs.com/xqnq2007/p/8204975.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值