Python HTML Email:如何在HTML电子邮件中插入列表项

时间:2013-05-28 10:01:14

标签: python smtplib

我努力寻找这个问题的解决方案,但一切都在静脉中,最后我不得不问你们。我有HTML电子邮件(使用Python的smtplib)。这是代码

Message = """From: abc@abc.com>
To: abc@abc.com>
MIME-Version: 1.0
Content-type: text/html
Subject: test

Hello,
Following is the message 
""" + '\n'.join(mail_body)  + """
Thank you.
"""

在上面的代码中,mail_body是一个包含进程输出行的列表。现在我想要的是,在HTML电子邮件中显示这些行(逐行)。现在发生了什么,它只是追加线。即。

我正在存储输出(进程),如下所示:

for line in cmd.stdout.readline()
    mail_body.append()

HTML电子邮件中的当前输出是:

Hello,
abc
Thank you.

我想要的是什么:

Hello,
a
b
c
Thank you.

我只想逐行将我的流程输出附加到HTML电子邮件中。我的输出能否以任何方式实现?

谢谢和问候

2 个答案:

答案 0 :(得分:2)

在HTML中,对于“换行符”,新行不是\n <br>,但由于您还没有在此电子邮件中使用HTML标记,因此您还需要知道在MIME邮件中,换行符为\r\n,而不仅仅是\n

所以你应该写:

'\r\n'.join(mail_body)

对于处理MIME邮件的换行符,但如果您要使用HTML进行格式化,则需要知道<br>是换行符,它将是:

'<br>'.join(mail_body)

为了全面,您可以尝试:

'\r\n<br>'.join(mail_body) 

但我现在知道那会是什么样的......

答案 1 :(得分:1)

您可以使用email package (from stdlib) e.g.生成要发送的电子邮件内容:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from cgi import escape
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP_SSL

login, password = 'me@example.com', 'my password'

# create message
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ', '.join([login,])

# Create the body of the message (a plain-text and an HTML version).
text = "Hello,\nFollowing is the message\n%(somelist)s\n\nThank you." % dict(
    somelist='\n'.join(["- " + item for item in mail_body]))

html = """<!DOCTYPE html><title></title><p>Hello,<p>Following is the message 
<ul>%(somelist)s</ul><p>Thank you. """ % dict(
    somelist='\n'.join(["<li> " + escape(item) for item in mail_body]))

# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(MIMEText(text, 'plain', 'utf-8'))
msg.attach(MIMEText(html, 'html', 'utf-8'))    

# send it
s = SMTP_SSL('smtp.mail.example.com', timeout=10) # no cert check on Python 2

s.set_debuglevel(0)
try:
    s.login(login, password)
    s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
    s.quit()