You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3使用smtplib发送HTML邮件出现多余!字符问题求助

问题原因

你遇到的多余!字符是SMTP协议的行长度限制导致的:
RFC 2821规范明确要求SMTP传输的每行内容长度不能超过1000字符(包含末尾的换行符)。你使用默认的7bit内容传输编码时,如果合并后的HTML存在超长单行,邮件服务器或者Python的email库会自动在超长位置插入!加换行符完成截断,最终就会在邮件展示时出现多余的!字符。

解决方法

按照以下步骤修改即可解决问题:

  • 显式指定邮件内容的编码为utf-8,避免默认的us-ascii编码兼容问题
  • 将内容传输编码从默认的7bit修改为quoted-printable或base64,自动处理超长行问题
  • 修正原有代码中的拼写错误、变量未定义等语法问题
修正后的参考代码
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders

AUTH_FROM_EMAIL = 'abc@email.com'
MAIL_HOST = 'smtp-abc.net'

def drop_email(sfrom=None, lstto=None, subj=None, body=None):
    msg = MIMEMultipart('alternative')
    # 修正邮件头赋值错误
    msg['Subject'] = subj
    msg['From'] = sfrom
    msg['To'] = ','.join(lstto)

    ishtml = 'html' in body.lower()
    # 显式指定utf-8编码
    text_part = MIMEText(body, 'html' if ishtml else 'plain', 'utf-8')
    # 修改传输编码为quoted-printable,处理超长行
    encoders.encode_quopri(text_part)
    msg.attach(text_part)

    s = smtplib.SMTP(MAIL_HOST)
    s.sendmail(AUTH_FROM_EMAIL, lstto, msg.as_string())
    s.quit()

def main():
    sfrom = 'abc.text@abc.com'
    sto1 = 'next.time@abc.com'
    # 显式指定编码读取HTML文件,避免乱码
    with open('abc.html', 'r', encoding='utf-8') as html_file:
        html = html_file.read()
    subj = 'hello'
    try:
       drop_email(sfrom, [sto1], subj, html)
    except Exception as e:
       print(e)

if __name__ == "__main__":
    main()

内容的提问来源于stack exchange,提问作者unknown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:48:03