Search code examples
pythonemailemail-attachmentsmime

How to attach files with space in filename when sending email


I am developing a Python application to send email. I follow this tutorial and attach with this code:

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...

The code runs and send the email. When the user adds an attachment, such as my attachment.pdf, the receiver sees my as the name of the attachment and their client does not show a preview of the attachment.

When I replace spaces in the filename with %20, the receiver sees a preview of the file but also sees %20 in the filename.

How can I attach files with spaces in the filename?


Solution

  • Put the filename in quotes:

    p.add_header('Content-Disposition', 'attachment; filename="%s"' % filename)