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

Building Dynamic HTML Email Content with Python

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

<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>

column1 和 column2 数据是关联字典中的键值对。

有没有简单的方法来做到这一点?这是一封通过 cronjob 发送的自动电子邮件,每天在填充数据后发送一次。

谢谢大家。 P.S 我对降价一无所知:/

P.S.S 我用的是Python 2.7

基本示例:使用模板

#!/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()

相关文档:

注意:假定您在本地系统上有一个有效的MTA

另请注意:您实际上可能想在撰写电子邮件时使用多部分消息;参见 Examples

更新: 顺便说一句,有一些非常好的(呃)"email sending" 库可能对您感兴趣:

我相信这些库与 requests -- SMTP for Humans

您可以利用的另一个工具(我的公司正在生产中使用)是 Mandrill。这是 Mailchimp 提供的一项服务,但它提供 "transactional" 电子邮件,即单独的个性化电子邮件,而不是群发电子邮件时事通讯。它对您每月发送的前 10,000 封电子邮件是免费的,让您从管理私人电子邮件服务器的负担中解脱出来,并提供一些非常好的 WYSIWYG 编辑工具、自动打开率和点击率跟踪,以及干净、简单 python API。

我公司使用的工作流程是:

  1. 使用 Mailchimp 中的所见即所得编辑器创建模板。稍后可以在运行时将动态数据插入到模板中,如 "merge vars".

  2. 将该模板从 Mailchimp 导入 Mandrill

  3. 使用cronjob python脚本获取动态数据并发送到Mandrill服务器发送出去。

示例 python 使用官方 Mandrill Python 库的代码:

import mandrill
mandrill_client = mandrill.Mandrill(mandrill_api_key)
message = {
    'from_email': 'gandolf@email.com',
    'from_name': 'Gandolf',
    'subject': 'Hello World',
    'to': [
        {
            'email': 'recipient@email.com',
            'name': 'recipient_name',
            'type': 'to'
        }
    ],
    "merge_vars": [
        {
            "rcpt": "recipient.email@example.com",
            "vars": [
                {
                    "name": "merge1",
                    "content": "merge1 content"
                }
            ]
        }
    ]
}
result = mandrill_client.messages.send_template(template_name="Your Template", message=message)