Send a list to HTML Email

末鹿安然 提交于 2019-12-08 13:52:05

问题


I am currently working with a HTML email document. Now I want to present a list with information from my database. How do I present the list in a HTML email? I've tried following:

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

I appreciate all the help. Thanks in advance.


回答1:


It seems to me like you're trying to use the jinja2 synthax without knowing it. You can either follow jinja2 Introduction in order to include it into your code, or just append articles to your html string with a simple loop, something like that:

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)



回答2:


As noamyg mentioned, seems you want to use a jinja stlye template in your html variable, without using the package.

From the jinja2 documentation.

from jinja2 import Template
template = Template('Hello {{ name }}!')
template.render(name='John Doe')
> 'Hello John Doe!'

So for your example import jinja2, use your html string as template and render it with your articles variable.



来源:https://stackoverflow.com/questions/56103530/send-a-list-to-html-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!