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