Python使用MIME发送Excel文件作为附件无法正常打开的问题求助
问题根因
- 附件配置的
Content-Disposition头中,filename参数被写为固定字符串file,没有使用实际的文件名,也没有带.xlsx后缀,邮件客户端无法识别文件格式,所以无法正常打开。 - 可选优化:Excel文件可使用更精准的MIME类型,提升客户端兼容性。
- 额外注意:你当前使用的Gmail SMTP服务缺少TLS开启和账号验证逻辑,实际运行可能会发送失败,修正代码中补充了对应逻辑。
修正后完整代码
import pandas as pd import smtplib import os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders sender='sender@email.com' receivers='receiver@email.com' # 生成正文用的测试数据表 d={'name':['alex','steve'], 'age':[23,45]} df=pd.DataFrame(data=d) msg = MIMEMultipart() msg['Subject'] = 'Email Test subject' msg['From'] = sender msg['To'] = receivers html=''' <html><p>******This is an Automated Email******</p> <h3>Updates pending:</h3> <p>Here is your table:</p> {0} <p></p><p> More text here.</p></html> '''.format(df.to_html()) msgText = MIMEText(html,'html') msg.attach(msgText) file = r'C:\Users\alo\Desktop\Python_Scripts\Excel\excel_file.xlsx' # 自动从路径中提取带后缀的文件名,避免硬写错误 file_name = os.path.basename(file) # 使用Excel专属MIME类型 part = MIMEBase('application', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet') part.set_payload(open(file, "rb").read()) encoders.encode_base64(part) # 传参指定文件名,不要写死在字符串中 part.add_header('Content-Disposition', 'attachment', filename=file_name) msg.attach(part) try: with smtplib.SMTP('smtp.gmail.com', 587) as smtpObj: smtpObj.starttls() # 开启TLS加密,Gmail要求必须开启 smtpObj.login(sender, "你的Gmail授权码") # Gmail需使用授权码登录,不能直接用账号密码 smtpObj.sendmail(sender, receivers, msg.as_string()) except Exception as e: print(e)
内容的提问来源于stack exchange,提问作者chulo
相关产品推荐
相关产品推荐

