向emai添加多个内联部件

2024-04-19 23:04:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.7,并尝试使用smtplib/MIMEMultipart发送电子邮件。我想发送一封包含多个部分的电子邮件,例如,一个文本消息和一个html消息。我不想让他们成为替代品。我想让它显示文本消息(inline)后跟html(inline)

在未来,我还想包括图像。因此,消息将包含文本、html和图像,所有这些都是内联的。在

这是我目前所拥有的,它生成一条文本消息,然后将html作为附件

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

s = smtplib.SMTP('localhost')

#this part works
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = from
msg['To'] = to

html_str = """<html><head></head><body><p>Test</p></body></html>"""

#this shows up with "This is my text" inline and the html as an attachment
text = MIMEText("This is my text", 'plain')
html = MIMEText(html_str, 'html')

msg.attach(text)
msg.attach(html)

s.sendmail(fromEmail, toEmail, msg.as_string())
s.quit()

如何在电子邮件中添加多个内联片段? 谢谢你的帮助


Tags: textfrom图像文本import消息电子邮件email
1条回答
网友
1楼 · 发布于 2024-04-19 23:04:18

我不能完全按照我的意愿去做,但我找到了一个解决办法。在

最后我把整个电子邮件变成了一个html电子邮件。对于我需要添加的每一个部分,我只需要添加html代码。例如,下面是我如何添加一个图像

html_list.append('<img src="cid:image.png">')
img = MIMEImage(my_data)
img.add_header('Content-ID', '<image.png>')
msg.attach(img)

如果我想添加文本,我可以将其添加为头(例如<h3>My Text</h3>)或任何其他html元素。在

相关问题 更多 >