Search code examples
pythonemailsmtplib

Send a list to HTML Email


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.


Solution

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