1

I'm trying to send an HTML email using smtplib. But I need the HTML content to have a table that is populated using values from a dictionary. I did look at the examples on the Python website. But it doesn't explain how to embed Python code within HTML. Any solutions/suggestions?

I also looked at this question. Can I just format it this way?

.format(dict_name)

Community
  • 1
  • 1
Ashwin
  • 873
  • 2
  • 12
  • 21
  • 1
    possible duplicate of [Sending HTML email using Python](http://stackoverflow.com/questions/882712/sending-html-email-using-python) – AechoLiu Sep 30 '15 at 07:52

2 Answers2

5

From your link:

Here’s an example of how to create an HTML message with an alternative plain text version: 2

import smtplib

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

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

and the sending section of it:

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

Edit 2022: for new comers, please advise with python’s latest stable release docs.

0x90
  • 39,472
  • 36
  • 165
  • 245
0

What you need is a template engine. That is, you need a python library that reads a file written in both HTML and code, interprets the code written within the HTML file (e.g. code that retrieves values from a dictionary), and then produces an HTML file for you.

The python wiki seems to have some suggestions

Jake Greene
  • 5,539
  • 2
  • 22
  • 26