我正在使用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())
答案 0 :(得分:1)
您的消息必须是multipart / alternative类型。默认的多部分子类型是&#34;混合&#34;。 试试这个:
msg = MIMEMultipart("alternative")