使用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'(打开文件,所以你基本上破坏了它

继我对您上一个问题的回答之后,这里是您的代码的重构版本,以使用现代的Python 3.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)

正如您所注意到的,与Python 3.5或更早版本中较旧的Email.MessageAPI相比,样板文件要少得多。

一种常见的安排是具有具有正文和附件的multipart/related消息,但是正文被表示为具有消息的text/plaintext/html呈现的multipart/alternative结构。如果你想要这个;芦笋";email模块文档的示例页面中的示例包含一个说明这一点的配方(尽管它还包括一个图像而不是二进制附件,并在HTML附件中内联显示(。

顺便说一句,你最好选择一种比Excel更不笨重的格式来共享数据。如果它只是一个表,CSV文本文件会小得多,也更容易在接收端处理。(如果您发送Excel,可能实际上使用其指定的MIME类型,而不是通用的application/octet-stream。(

相关内容

  • 没有找到相关文章

最新更新