python - 如何使用 python 在电子邮件正文中附加 HTML

标签 python html email outlook

我正在使用 python 自动发送邮件,并且运行良好。当我尝试将 html 添加到电子邮件正文中时,问题就出现了。 HTML 代码作为附件添加到 Outlook 邮件中,而不是嵌入到正文中。我该如何克服这个问题?

from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import smtplib
import sys


recipients = ['abc@emaxple.com','def@example.com'] 
emaillist = [elem.strip().split(',') for elem in recipients]
msg = MIMEMultipart()
msg['Subject'] = str("Trial")
msg['From'] = 'abc@example.com'

msg.preamble = 'Multipart massage.\n'

html="""<html><body><p>Hi!</p>
<a href="www.google.com">Google</a>
</body></html>"""

part2=MIMEText(html,'html') 

part = MIMEText("Hello")

msg.attach(part)
msg.attach(part2)

for excel_file_location in sys.argv[1].split(","):
    part = MIMEApplication(open(str(excel_file_location),"rb").read())
    part.add_header('Content-Disposition', 'attachment', filename=str(excel_file_location.split("\\")[-1]))
    msg.attach(part)


server = smtplib.SMTP("smtp.office365.com",587)
server.ehlo()
server.starttls()
server.login("abc@example.com", "asdgfasgas")

server.sendmail(msg['From'], emaillist , msg.as_string())

最佳答案

您的消息必须是 multipart/alternative 类型。默认的多部分子类型是“混合”。 试试这个:

msg = MIMEMultipart("alternative")

关于python - 如何使用 python 在电子邮件正文中附加 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41280607/

相关文章:

css - href#section 标签在 safari 中不起作用

php - 通过 PHP 在电子邮件中发送 HTML

swift - 单击“取消”或“删除草稿”后关闭邮件 View Controller

当某些线程创建 Webdriver 时 Python Selenium 失败

python - Selenium 网络驱动程序 python : Element is not clickable at point

python - 如何在python中获取行基础行总计中每个值的百分比

html - youtube iframe 的响应对齐?

Python - 越来越快地运行程序

html - 创建左侧带有基于 unicode 的图标的框

php - 调试 mySQLi 准备好的语句 -> 未找到电子邮件