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

Python发送带.xlsx附件邮件时触发TypeError报错问题咨询

问题原因
  • df.to_csv()不传路径参数时,默认直接返回CSV格式的字符串内容,所以直接传入MIMEApplication作为附件内容可以正常运行。
  • df.to_excel()没有该默认返回逻辑,方法定义中第一个参数excel_writer是必填项,要求传入文件保存路径或可写入的类文件对象,空参调用时就会抛出TypeError: to_excel() missing 1 required positional argument: 'excel_writer'错误。
修复方案

不需要把Excel文件落地保存到本地磁盘,借助Python标准库的io.BytesIO创建内存字节流作为excel_writer参数即可,步骤如下:

  1. 先安装xlsx格式读写依赖:执行命令pip install openpyxl
  2. 代码开头新增导入内存流模块import io
  3. 替换原代码中生成CSV附件的逻辑,将DataFrame写入内存流后读取二进制内容作为Excel附件

修改后的完整可运行代码:

from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import io  # 新增内存流模块导入

def send_email(send_to, subject, df):
    send_from = "xxx.xxx@hotmail.fr"
    password = "xxx"
    message = """\
    <p><strong>This is a test email&nbsp;</strong></p>
    <p><br></p>
    <p><strong>Greetings&nbsp;</strong><br><strong>Alexandre&nbsp;</strong></p>
    """

    multipart = MIMEMultipart()
    multipart["From"] = send_from
    multipart["To"] = send_to
    multipart["Subject"] = subject  
    
    # 生成Excel附件逻辑
    buffer = io.BytesIO()
    # 写入Excel到内存流,index=False可取消导出默认行序号,可按需调整
    df.to_excel(buffer, index=False, engine='openpyxl')
    # 将流指针移到起始位置,保证读取到完整文件内容
    buffer.seek(0)
    attachment = MIMEApplication(buffer.getvalue())
    attachment["Content-Disposition"] = 'attachment; filename=" {}"'.format(f"{subject}.xlsx")
    
    multipart.attach(attachment)
    multipart.attach(MIMEText(message, "html"))
    server = smtplib.SMTP("smtp-mail.outlook.com", 587)
    server.starttls()
    server.login(multipart["From"], password)
    server.sendmail(multipart["From"], multipart["To"], multipart.as_string())
    server.quit()
        
send_email("xxx.xxx@hotmail.fr", "Covid-19 data per country", ListeProjetsCodeNovaMergefinal)

小提示:如果需要导出为旧版.xls格式,把引擎参数换成xlwt即可,日常使用优先选xlsx格式兼容性更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 12:03:17