【问题标题】:How to embed a CSV file into an HTML table inside an email?如何将 CSV 文件嵌入到电子邮件中的 HTML 表格中?
【发布时间】:2020-10-08 19:46:47
【问题描述】:

我正在使用 Python 中的 email 包发送一些电子邮件。我可以发送带有 .csv 附件的电子邮件,但它们总是出现在电子邮件的顶部。但是,我需要将附件嵌入表格中,但我不知道如何。我希望它看起来像这样: Example email with attachment

这是我目前使用的代码:

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

msg = MIMEMultipart('alternative')
msg['From'] = 'from@example.com'
msg['To'] = 'to@example.com'
msg['Subject'] = 'Request'

with open('dataexample.csv') as attachment:
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(attachment.read())

# Add header
part.add_header("Content-Disposition", f"attachment; filename= dataexample.csv",)
encoders.encode_base64(part)
msg.attach(part)

# html version of message
html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table {
        border-collapse: collapse;
        }
        table, td {
        border: 1px solid black;
        }
    </style>
</head>
<body>
<table style="width:100%;">
    <tr>
        <td>First Column First Row</b></td>
        <td>Second Column First Row</td>
    </tr>
    <tr>
        <td>First Column Second Row</td>
        <td></td>  # i want the csv file to be embedded in this cell of the table
</table>
</body>
</html>
"""

msg.attach(MIMEText(html, 'html'))
server = smtplib.SMTP(host='host', port=25)
server.send_message(msg)

【问题讨论】:

  • 唯一的方法是使用 html 锚标签 + 托管在某些公共网络服务器上的 csv 文件。
  • @JiříOujezdský 所以附件不会嵌入到电子邮件中?而是指向附件的链接?
  • 是的,指向公共网络服务器上托管文件的 html 链接。

标签: python html email mime smtplib


【解决方案1】:

您可以使用Pandas 获取 CSV 文件的 HTML 字符串表示:

import pandas as pd

df = pd.read_csv('my.csv', header=None) # change options if needed...
html = df.to_html() # also has lots of nifty options

请参阅pandas.read_csvpandas.DataFrame.to_html

您可以将该字符串附加到电子邮件所需的任何其他内容中。

【讨论】:

  • 对不起,我可能不太清楚。我需要 csv 作为表格内的附件,而不是表格内的数据框。它需要看起来像这样的图片:i.stack.imgur.com/dYMR8.png
猜你喜欢
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 2017-12-03
  • 2012-06-17
  • 1970-01-01
  • 2012-05-10
  • 2011-07-12
相关资源
最近更新 更多