代码中没有错误。它确实通过电子邮件发送了带有.xlsx附件的电子邮件。但是当我打开附件时,它说文件已损坏,无法打开它。我不知道错误在哪里可以帮助您?
import smtplib
import base64
filename = "X:\MADHAV\File_Request\Dept_master Original.xlsx"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'HOUHDCDOVERITDL@gmail.com'
reciever = 'vadalm@gmail.com'
marker = "DEPTMASTER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From HOUHDCDOVERITDL <HOUHDCDOVERITDL@gmail.com>
To: To vadalm@arconic.com <vadalm@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: xlsx
Content-Transfer-Encoding:xlsx
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64(xlsx)
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print ("Successfully sent email")
except Exception:
print ("Error: unable to send email")