【问题标题】:Email attachment file names are removed with AT00001使用 AT00001 删除电子邮件附件文件名
【发布时间】:2020-01-30 15:53:55
【问题描述】:

发送带有多个附件的邮件会删除附件文件名。附件名称更改为 ATT00001.xlsx。根据以下链接,在附件之前添加了“正文”部分,但没有运气。

https://exchange-server-guide.blogspot.com/2015/11/att00001.txt-file-fix-email-attachment-issue.html

供参考,分享如下代码sn-p。任何建议表示赞赏。

msg = MIMEMultipart()
ctype = content_type
maintype, subtype = ctype.split('/', 1)
msg['Subject'] = subject
msg['To'] = 'abc@sample.com'
msg['From'] = sender
smtp_client = smtplib.SMTP(smtp_host + ':' + smtp_port)
smtp_client.starttls()
smtp_client.login(sender, smtp_login_password)
body_part = MIMEText(body, 'plain')
msg.attach(body_part)
for file_path in file_paths :
    temp_arr = file_path.split('/')
    file_name = temp_arr[len(temp_arr) - 1]
    msg.add_header('Content-Disposition', 'attachment', filename=file_name)
    fp = open(file_path, 'rb')
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encode_base64(attachment)
    msg.attach(attachment)
smtp_client.sendmail(sender, 'abc@sample.com', msg.as_string())
smtp_client.quit() 

【问题讨论】:

  • 这里有很多缺失的imports 和未声明的变量。 SMTP 发送部分并不是真正需要的(并且在适当的模块化代码中不应与消息组合代码纠缠在一起)。查看提供minimal reproducible example的指南

标签: python python-3.x email smtp smtplib


【解决方案1】:

您正在将Content-Disposition: 添加到多部分容器中。您应该将它添加到每个单独的身体部位。

改变这个:

for file_path in file_paths :
    temp_arr = file_path.split('/')
    file_name = temp_arr[len(temp_arr) - 1]
    msg.add_header('Content-Disposition', 'attachment', filename=file_name)
    fp = open(file_path, 'rb')
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encode_base64(attachment)
    msg.attach(attachment)

类似

for file_path in file_paths:
    file_name = file_path.split('/')[-1]
    attachment = MIMEBase(maintype, subtype)
    with open(file_path, 'rb') as fp:
        attachment.set_payload(fp.read())
    attachment.add_header('Content-Disposition', 'attachment', filename=file_name)
    encode_base64(attachment)
    msg.attach(attachment)

我还冒昧地切换到使用上下文管理器(with 语句)。我还简化了文件名提取。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-08-01
  • 1970-01-01
  • 2013-06-14
  • 2015-05-28
  • 1970-01-01
  • 2017-03-31
  • 2013-02-07
  • 1970-01-01
相关资源
最近更新 更多