Angus Gray
Angus Gray

Reputation: 443

Sending xlsx file using SMTP & Python 3

I'm having trouble getting the SMTP server to keep my filenames as I attach them to emails and send them. I ran this twice, and it worked perfectly. The name and excel sheet showed as they were supposed to. Now, no matter what I do, the attachment is always something like ATT00001.xlsx when it used to work just fine. (literally left for lunch break and re-ran it when I got back with no changes) I'm wondering if it's how i'm attaching the excel sheet to my email. Would anyone happen to know what's going on with this? Thanks!

msg = MIMEMultipart()
sender='[email protected]'
recipients='[email protected]'
server=smtplib.SMTP('mail.server.lan')

msg['Subject']='Quarterly Summary'
msg['From']=sender
msg['To']=recipients



filename = r'C:\Users\user.chad\Quarterly\project\output\MyData.xlsx'
attachment = open(r'C:\Users\user.chad\Quarterly\project\output\MyData.xlsx', 'rb')
xlsx = MIMEBase('application','vnd.openxmlformats-officedocument.spreadsheetml.sheet')
xlsx.set_payload(attachment.read())

encoders.encode_base64(xlsx)
xlsx.add_header('Content-Dispolsition', 'attachment', filename=filename)
msg.attach(xlsx)

server.sendmail(sender, recipients, msg.as_string())
server.quit()
attachment.close()

Upvotes: 2

Views: 7288

Answers (2)

Carl Zheng
Carl Zheng

Reputation: 728

This is an example to add an attachment with text/html conent.

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

message = MIMEMultipart()

# add text
message.attach(
    MIMEText(
        content,
        'html',
        'utf-8'
        )
    )

# add attachment
attachment = MIMEBase('application', "octet-stream")
# open a file to attach
attachment.set_payload(open(filepath, "rb").read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % self.filename )
message.attach(attachment)


server.sendmail(SENDER, receivers, message.as_string())

Upvotes: 0

E.Serra
E.Serra

Reputation: 1574

Just for the record:

xlsx.add_header('Content-Dispolsition', 'attachment', filename=filename)

should be

xlsx.add_header('Content-Disposition', 'attachment', filename=filename)

Upvotes: 3

Related Questions