Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email attachment name in outlook always "AT00001.xlsx" instead of actual name when sent from python script

Tags:

python

mime

smtp

I'm trying to send an email with an attachment from a python script. The email arrives at my inbox with all the correct recipients, subject, body, and data in the attachment

The issue is that the attachment file name is always "AT00001.xlsx" instead of the file name in the script.

Here is the method I am calling to send the email:

def send_email():

    msg = MIMEMultipart()

    message = "Here is your file"

    msg['From'] = MY_ADDRESS
    msg['To'] = MY_ADDRESS
    msg['Subject'] = "File extract"
    msg.attach(MIMEText(message))

    attach_file_name = "test.xlsx"
    attach_file = open(attach_file_name, "rb")

    payload = MIMEBase('application', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    payload.set_payload(attach_file.read())

    attach_file.close()
    encoders.encode_base64(payload)

    payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
    msg.attach(payload)

    s = smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
    s.starttls()
    s.login(MY_ADDRESS, PASSWORD)

    s.sendmail(MY_ADDRESS, MY_ADDRESS, msg.as_string())
    s.quit()

I've found post on various websites that describe this issue happening due to the attachment and text being out of order. I verified that the attachment is last in the email payload, so I don't think this is what is causing it.

like image 475
Zach Avatar asked Sep 01 '25 05:09

Zach


1 Answers

As rfkortekaas pointed out in his comment, the cause of this problem was I was using ‘Content-Decomposition’ instead of ‘Content-Disposition’.

I updated this line of code and it worked perfectly:

payload.add_header('Content-Disposition', 'attachment', filename=attach_file_name)
like image 194
Zach Avatar answered Sep 02 '25 17:09

Zach