Python中的HTML电子邮件

时间:2013-04-04 03:57:29

标签: python smtplib

我正在尝试使用smtplib发送HTML电子邮件。但我需要HTML内容有一个使用字典值填充的表。我确实查看了Python网站上的示例。但它没有解释如何在Python中嵌入Python代码。任何解决方案/建议?

我也看了this个问题。我可以这样格式化吗?

.format(dict_name)

2 个答案:

答案 0 :(得分:4)

从你的link(这里遗漏了一些东西):

  

以下是如何使用替代方法创建HTML消息的示例   纯文本版本:[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>
"""

及其发送部分:

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

答案 1 :(得分:0)

您需要的是模板引擎。也就是说,你需要一个python库来读取用HTML和代码编写的文件,解释HTML文件中编写的代码(例如从字典中检索值的代码),然后为你生成一个HTML文件。

The python wiki seems to have some suggestions