首页 > 解决方案 > 将列表发送到 HTML 电子邮件

问题描述

我目前正在处理 HTML 电子邮件文档。现在我想提供一个包含我数据库中信息的列表。如何在 HTML 电子邮件中显示列表?我试过以下:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

articles = ['hello', 2, 5, 'bye']

me = "email@gmail.com"
you = "email@gmail.com"
subject = 'something'

msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = me
msg['To'] = you

html = """\

    {% for i in {articles} %}
        <p> {{ i }} </p>
    {% endfor %}

""".format(articles)

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login("email@gmail.com", "password")

server.sendmail(me, you, msg.as_string())
server.quit()

我感谢所有的帮助。提前致谢。

标签: pythonemailsmtplib

解决方案


在我看来,您似乎正在尝试在不知情的情况下使用jinja2 合成器您可以按照 jinja2 Introduction 将其包含到您的代码中,也可以articles使用简单的循环将其附加到您的 html 字符串中,如下所示:

articles = ['hello', 2, 5, 'bye']

html = """\
<html>
  <body>
    <table>
      <tbody>
        {}
      </tbody>
    </table>
  </body>
</html>
"""

rows = ""
for article in articles:
    rows = rows + "<tr><td>"+str(article)+"<td></tr>"
html = html.format(rows)

推荐阅读