You need to enable JavaScript to run this app. Python smtplib发送xlsx附件 Gmail可见但Thunderbird不显示
优惠活动
大模型
产品
解决方案
定价
更多

Python smtplib发送xlsx附件 Gmail可见但Thunderbird不显示

邮件附件Thunderbird不显示的根因与修复

核心问题根因

  • 外层MIME容器类型不符合规范
    原代码使用MIMEMultipart('alternative')作为邮件根容器,该类型的语义是“内部组件为可互换的正文版本(纯文本/HTML)”。严格遵循MIME规范的Thunderbird会自动忽略该容器中不属于正文类型的组件,导致挂载在其中的附件直接被过滤。Gmail的兼容性更宽松,会额外解析这类错位挂载的附件,因此网页版中可正常查看。
  • MIME类型存在拼写错误
    原代码附件类型写为application/octet-stram,正确的二进制流类型应为application/octet-stream(漏写字母e,拼写错误)。识别失败的MIME类型会触发Thunderbird的内容拦截规则。
  • 附件头格式不兼容严格校验规则
    原代码的附件头写法为attachment; filename= {filename},存在两个问题:filename字段前多了多余空格,且未按照RFC规范对带空格的文件名做编码处理。Thunderbird会将解析失败的组件判定为正文内容,而非独立附件。
  • 结构层级错位
    原代码将附件直接挂载到alternative正文容器下,不符合“附件需挂载到mixed根容器”的标准邮件结构要求。

修复后兼容所有主流客户端的代码

import smtplib, ssl
from email import encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.utils import formataddr


def enviar_email(email):
    smtp_server = 'smtp.gmail.com'
    port = 465
    sender = 'proex.crim@gmail.com'
    password = '**********'
    receiver = email
    context = ssl.create_default_context()

    # 根容器使用mixed类型,兼容带附件的多部分邮件结构
    message = MIMEMultipart('mixed')
    message['Subject'] = 'Pesquisa finalizada'
    message['From'] = formataddr(('Proex', sender))
    message['To'] = receiver

    # 正文部分使用alternative子容器承载纯文本/HTML两个版本
    body_container = MIMEMultipart('alternative')
    local_file_path = f'C:\\Users\\evand\\OneDrive\\Desktop\\projeto\\core\\funcoes\\{email}.xlsx'
    attachment_display_name = 'Resultado da Pesquisa.xlsx'

    text_content = """\
        Olá, segue em anexo o resultado da pesquisa solicitada no nosso site. 
        Enviamos para você um arquivo com os processos correspondentes aos CNPJs pesquisados.
    """

    html_content = """\
        <html>
            <body>
            <p> Olá, segue em anexo o resultado da pesquisa solicitada no nosso site. <br>
            </p>
            <p> Enviamos para você um arquivo com os processos correspondentes aos CNPJs pesquisados.</p>
        </body>
    </html>
    """

    body_container.attach(MIMEText(text_content, 'plain'))
    body_container.attach(MIMEText(html_content, 'html'))
    message.attach(body_container)

    # 处理xlsx附件
    with open(local_file_path, 'rb') as attachment_file:
        attachment_part = MIMEBase('application', 'octet-stream')
        attachment_part.set_payload(attachment_file.read())

    encoders.encode_base64(attachment_part)
    # 按RFC规范生成附件头,自动完成文件名编码,无多余空格
    attachment_part.add_header(
        'Content-Disposition',
        'attachment',
        filename=('utf-8', '', attachment_display_name)
    )
    # 附件直接挂载到根mixed容器
    message.attach(attachment_part)

    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
        server.login(sender, password)
        server.sendmail(sender, receiver, message.as_string())

修复说明

  • 调整后的邮件结构完全符合RFC 5322、RFC 2045标准,Thunderbird、Outlook、Foxmail等严格校验MIME格式的客户端均可正常识别附件。
  • 附件头采用Python email库内置的RFC编码逻辑,自动适配带空格、特殊字符、非ASCII语言的文件名,不会出现解析失败的问题。
  • 拆分了本地文件路径和附件展示名的变量,消除了原代码中变量复用导致的隐性维护风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 07:36:05