我正在使用Python中的email
包发送一些电子邮件。我可以发送带有.csv附件的电子邮件,但它们总是出现在电子邮件的顶部。但是,我需要将附件嵌入表中,但我不知道如何。我希望它看起来像这样: 带附件的示例电子邮件
这是我目前使用的代码:
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)
您可以使用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_csv和 熊猫。DataFrame.to_html
您可以将该字符串附加到电子邮件所需的任何其他内容中。