使用Python构建动态HTML电子邮件内容 [英] Building Dynamic HTML Email Content with Python

查看:216
本文介绍了使用Python构建动态HTML电子邮件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python字典,我想用两列表的形式发送电子邮件,其中有一个Title和两个列标题,并将字典的key-value对填充到行.

I have a python dictionary that I'd like to send an email with in the form of a two column table, where I have a Title and the two column headers, and the key,value pair of the dictionary populated into the rows.

<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数据是关联字典中的键,值对.

The column1 and column2 data are the key,value pairs from the associated dictionary.

有没有一种简单的方法可以做到这一点?这是每天填充一次后通过cronjob发送的自动电子邮件.

Is there a way to do this in a simple manner? This is an auotmated email being sent out via a cronjob, once a day after populating the data.

谢谢大家. 附言:我对减价一无所知:/

Thank you all. P.S I know nothing about markdown :/

P.S.S我正在使用Python 2.7

P.S.S I am using 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()

相关文档:

  • Jinja2
  • email.mime.text
  • smeplib

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

NB: This assumes you have a valid MTA on your local system.

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

Note Also: That you may in fact actually want to use a multipart message when composing the email; See Examples

更新:顺便说一句,那里有一些非常不错的电子邮件发送"库,您可能对此感兴趣:

Update: As an aside there are some really nice(er) "email sending" libraries out there that may be of interest to you:

  • sender
  • outbox
  • Envelopes

我相信这些库与请求相同-SMTP用于人类

I believe these libraries are along the same lines as requests -- SMTP for Humans

这篇关于使用Python构建动态HTML电子邮件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆