使用python将EXCEL文件附加到电子邮件中
问题描述
我试图通过电子邮件发送一个Excel文件,但不知何故格式和文本被更改了。我使用的是python3和MIMEMultipart()。
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
filename = "file_name.xlsx" # In same directory as script
# Open PDF file in binary mode
with open(filename, 'r') as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
message.attach(part)
text = message.as_string()
# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, 465 , context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, text)
解决方案
注释错误;您没有以二进制模式('rb'
)打开文件,因此基本上是在损坏它
根据我对your previous question的回答,这里是您的代码的重构版本,以使用现代的、Python3.6+EmailMessage
库。
from email.message import EmailMessage
...
message = EmailMessage()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.set_content(body, 'plain')
# The OS will look in the current working directory, not in the directory where you saved the script
filename = "file_name.xlsx"
# Notice 'rb'
with open(filename, 'rb') as attachment:
message.add_attachment(
attachment.read(),
maintype='application', subtype='octet-stream')
# AGAIN, no need for a context if you are just using the default SSL
with smtplib.SMTP_SSL(smtp_server, 465) as server:
server.login(sender_email, password)
# AGAIN, prefer the modern send_message method
server.send_message(message)
正如您所注意到的,与来自Python3.5或更早版本的较旧的Email.Message
API相比,它的样板要少得多。
multipart/related
消息,但是正文文本表示为具有text/plain
和text/html
呈现的multipart/alternative
结构。如果您想要这样做,email
module documentation's examples page中的&Quot;ASTOUUS&QOOT;示例包含了一个演示这一点的配方(尽管它还包含一个图像而不是二进制附件,并将其内联显示在HTML附件中)。
从长远来看,您最好选择一种不像Excel那样笨重的格式来共享数据。如果它只是一个表格,CSV文本文件将小得多,并且更容易在接收端进行处理。(如果您确实发送了Excel,则可能实际使用其指定的MIME类型,而不是泛型application/octet-stream
。)
相关文章