使用python SMTP函数将邮件附件扩展更改为.bin

2024-04-26 14:41:24 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用python和smtplib发送带有attachement(excel文档)的电子邮件时,attachement中的文档会丢失其扩展名,并无缘无故变成.bin文件

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders


Smail = "example@hotmail.com"
Smailpass = "password"
Rmail = "example@yahoo.com"

msg = MIMEMultipart()
msg['From'] = Smail
msg['To'] = Rmail
msg['Subject'] = "Subject of the Mail"
MailMSG = "this is a test py"

msg.attach(MIMEText(MailMSG, 'plain'))
# attach file
myfile = "document.xlsx"
attachment = open("custom directory/document.xlsx", "rb")

p = MIMEBase('application', 'octet-stream')
p.set_payload((attachment).read())
encoders.encode_base64(p)
p.add_header('Content-Decomposition', 'attachment, filename="document.xlsx"')
msg.attach(p)
# login and send
Mailserver = smtplib.SMTP("smtp.live.com", 587)
Mailserver.ehlo()
Mailserver.starttls()
Mailserver.login(Smail, Smailpass)
text = msg.as_string()
Mailserver.sendmail(Smail, Rmail, text)
Mailserver.quit()

Tags: textfromimportcomattachmentemailmsgxlsx
1条回答
网友
1楼 · 发布于 2024-04-26 14:41:24

你这里有多处打字错误

p.add_header('Content-Decomposition', 'attachment, filename="document.xlsx"')

头的名称是Content-Disposition,在处置后应该有一个分号,而不是逗号

p.add_header('Content-Disposition', 'attachment; filename="document.xlsx"')

曾经有一段时间,在Content-Disposition:头中指定文件名是不够的,因此一些客户端仍然有“皮带和吊杆”回退,并且还将; name="document.xslx"添加到Content-Type: application/octet-stream主体部分头中。也可以使用Excel的标准IANA内容类型;参见What is a correct mime type for docx, pptx etc?,其中建议application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

。。。总之,你应该看看

Content-Type: multipart/mixed; boundary="===============5298122497454831280=="
MIME-Version: 1.0
From: example@hotmail.com
To: example@yahoo.com
Subject: Subject of the Mail

 ===============5298122497454831280==
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit

this is a test py
 ===============5298122497454831280==
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;
     name="document.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="document.xlsx"

77+/dHJpcGzuu64=

 ===============5298122497454831280== 

(这里我用一个简单的占位符替换了base64数据)

(此外,Python愚蠢地坚持在每个主体部分添加MIME-Version:头,但这完全没有必要。)

相关问题 更多 >