发送邮件时如何附加文件名带空格的文件

问题描述 投票:0回答:1

我正在开发一个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

如何附加文件名中带有空格的文件?

python email email-attachments mime
1个回答
0
投票

将文件名放在引号中:

p.add_header('Content-Disposition', 'attachment; filename="%s"' % filename)
© www.soinside.com 2019 - 2024. All rights reserved.