gpt4 book ai didi

Python HTML 电子邮件 : How to insert list items in HTML email

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:08 25 4
gpt4 key购买 nike

我一直在努力寻找解决这个问题的方法,但都一帆风顺,最后我不得不问问你们。我有 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 电子邮件中逐行附加我的过程输出。我的输出可以以任何方式实现吗?

感谢和问候

最佳答案

您可以使用 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()

关于Python HTML 电子邮件 : How to insert list items in HTML email,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16789213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com