如何将pandas数据帧嵌入到具有HTML格式的SparkPost电子邮件中



我想通过SparkPost发送自动电子邮件,邮件正文中包含pandas数据帧。下面的代码显示了到目前为止我所做的工作。主要问题是传输块的html部分。如果我的html部分按原样格式化,我无法发送电子邮件,但如果我删除html变量中的所有当前文本并设置html=table,我可以运行电子邮件,但不包括html格式。

我的问题是如何将数据帧嵌入到html中?

from sparkpost import SparkPost
from sparkpost.exceptions import SparkPostAPIException
import pandas as pd
from tabulate import tabulate
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
table = tabulate(df, headers=list(df.columns.values), tablefmt="html")
sp = SparkPost('API Key here')
try:
response = sp.transmissions.send(
recipients=['recipient@email.com'],
html="""
<html>
<head>
<style> 
table, th, td {{ border: 1px solid black; border-collapse: collapse; }}
th, td {{ padding: 5px; }}
</style>
</head>
<body>
<p>Hello, <br><br>Please find the data below.</p>
<p>Here is your data:</p>
{table}
<p>Thanks,</p>
<p>Signature</p>
</body>
</html>
""",
from_email='sender@email.com',
subject='SparkPost Test Email'
)
except SparkPostAPIException as err:
# http response status code
print(err.status)
# python requests library response object
# http://docs.python-requests.org/en/master/api/#requests.Response
print(err.response.json())
# list of formatted errors
print(err.errors)

这对我有效

response = sp.transmissions.send(

recipients=['test@example.com'],
html="""
<html>
<head>
</head>
<body>
<p>Hello, <br><br>Please find the data below.</p>
<p>Here is your data:</p>""" +
table +
"""<p>Thanks,</p>
<p>Signature</p>
</body>
</html>
""",
from_email='sender@example.com',
subject='SparkPost Test Email'
)

相关内容

  • 没有找到相关文章

最新更新