0

I'm trying to sending email with attachment with below python code, but the xlsx attachment always broken in the email, I guess there's something wrong with the encoding, Content-Type and Content-Transfer-Encoding in part3 but I changed many Content-Type but still failed to open the xlsx attachment. Can anyone give some suggestion? thank you very much in advance!

I've seen the answer in add excel file attachment when sending python email

and I just want to know what's wrong with my code, and how to correct it to make the xlsx attachment openable.

#!/usr/bin/python

import smtplib
import base64

filename = "xxxx.xlsx"

# Read a file and encode it into base64 format
fo = open(filename, 'rb')
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = 'donotreply@xxxx.com'
reciever = 'xxxx@xxxx.com'

marker = "MARKER"

body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: xxxx <donotreply@xxxx.com>
To: <xxxx@xxxx.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

# Define the attachment section
part3 = """Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; name=\"%s\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP(host='xxxx.com',port=25)
   smtpObj.sendmail(from_addr=sender,to_addrs=reciever,msg=message)
   print ("Successfully sent email")
except Exception as e:
   print (e)
Eri Zhang
  • 1
  • 1
  • Does this answer your question? [add excel file attachment when sending python email](https://stackoverflow.com/questions/25346001/add-excel-file-attachment-when-sending-python-email) – Aditya Jun 28 '20 at 03:41
  • @Aditya Thanks Aditya, I've seen this post and it works, I just want to know what's wrong in my code, any comment is appreciated. – Eri Zhang Jun 28 '20 at 05:25

0 Answers0