使用Python构建动态HTML电子邮件内容

gan*_*olf 6 python html-email python-2.7

我有一个python字典,我想以两列表的形式发送电子邮件,其中我有一个标题和两个列标题,以及填充到行中的字典的键值对.

<tr>
<th colspan="2">
<h3><br>title</h3>
</th> </tr>
<th> Column 1 </th>
<th> Column 2 </th>
"Thn dynamic amount of <tr><td>%column1data%</td><td>%column2data%</td></tr>
Run Code Online (Sandbox Code Playgroud)

column1和column2数据是来自关联字典的键值对.

有没有办法以简单的方式做到这一点?这是在填充数据后每天一次通过cronjob发送的auotmated电子邮件.

谢谢你们.PS我对降价一无所知:/

PSS我使用的是Python 2.7

Jam*_*lls 8

基本实施例:(与模板)

#!/usr/bin/env python

from smtplib import SMTP              # sending email
from email.mime.text import MIMEText  # constructing messages

from jinja2 import Environment        # Jinja2 templating

TEMPLATE = """
<html>
<head>
<title>{{ title }}</title>
</head>
<body>

Hello World!.

</body>
</html>
"""  # Our HTML Template

# Create a text/html message from a rendered template
msg = MIMEText(
    Environment().from_string(TEMPLATE).render(
        title='Hello World!'
    ), "html"
)

subject = "Subject Line"
sender= "root@localhost"
recipient = "root@localhost"

msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient

# Send the message via our own local SMTP server.
s = SMTP('localhost')
s.sendmail(sender, [recipient], msg.as_string())
s.quit()
Run Code Online (Sandbox Code Playgroud)

相关文件:

注意:假设您在本地系统上拥有有效的MTA.

另请注意:实际上,您在编写电子邮件时实际上可能希望使用多部分消息; 见例子

更新:除此之外,还有一些非常好的(呃)"电子邮件发送"库可能会让您感兴趣:

我相信这些库与请求一致 - 人类的SMTP