2013-04-04 26 views
1

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

我也看过this的问题。我可以用这种方式格式化吗?

.format(dict_name)

+1

可能重复(http://stackoverflow.com/questions/882712/sending-html-email-using-python) – AechoLiu 2015-09-30 07:52:44

回答

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 = "[email protected]" 
you = "[email protected]" 

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

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

The python wiki seems to have some suggestions

+1

不需要模板引擎。 – 2013-04-04 04:11:42

+0

可能不需要模板引擎,但允许开发人员将模型(Python代码与字典)和视图(电子邮件模板)的职责分开。 – 2013-04-04 04:17:14