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

2024-04-20 12:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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>

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

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

谢谢大家。 P、 我对降价一无所知

p.S.S我正在使用Python2.7


Tags: 数据br标题列表字典titlecolumndynamic
2条回答

基本示例:带模板

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

更新:除此之外,还有一些非常不错的(er)“电子邮件发送”库,您可能会感兴趣:

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

你可以利用的另一个工具(我的公司正在生产中使用)是Mandrill。这是Mailchimp提供的一项服务,但它提供的不是大量的电子邮件通讯,而是“事务性”电子邮件,即个人的、个性化的电子邮件。每月发送的前10000封电子邮件都是免费的,使您摆脱了管理私人电子邮件服务器的负担,还提供了一些非常好的所见即所得编辑工具、自动打开率和单击率跟踪以及干净、简单的python api。

我的公司正在使用的工作流是:

  1. 使用Mailchimp中的所见即所得编辑器创建模板。动态数据可以在运行时作为“合并变量”插入到模板中。

  2. 将该模板从Mailchimp导入Mandrill

  3. 使用cronjob python脚本检索动态数据并将其发送到要发送的Mandrill服务器。

使用官方Mandrill python库的示例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)

相关问题 更多 >