我正在开发一个Python应用程序来发送电子邮件。我按照本教程并附上以下代码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def prepare_attachment(filepath):
filename = os.path.basename(filepath)
attachment = open(filepath, "rb")
# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form.
p.set_payload((attachment).read())
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
return p
class Sender(object):
# other code...
def send(self):
msg = MIMEMultipart()
# other code...
# open the file to be sent
for attachment in self.attachments:
p = prepare_attachment(attachment)
# attach the instance 'p' to instance 'msg'
msg.attach(p)
# rest of code...
代码运行并发送电子邮件。当用户添加附件(例如
my attachment.pdf
)时,接收者会看到 my
作为附件的名称,并且他们的客户端不会显示附件的预览。
当我用
%20
替换文件名中的空格时,接收者会看到文件的预览,但也会在文件名中看到 %20
。
如何附加文件名中带有空格的文件?
将文件名放在引号中:
p.add_header('Content-Disposition', 'attachment; filename="%s"' % filename)