Python smtplib 无法附加多个 mimetext
Python smtplib cannot attach multiple mimetext
我无法弄清楚为什么我的 python 代码无法在同一封电子邮件中附加 HTML table(第 2 部分)和普通句子(第 1 部分)。我试着评论一行 message.attach(part2)
,反之亦然。 message
object.
有问题
port = 587 # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "xyz@gmail.com"
receiver_email = ["abc@qwer.com","def@gmail.com"]
password = getpass.getpass()
message = MIMEMultipart("alternative")
message["From"] = sender_email
message["To"] = ", ".join(receiver_email)
message["Subject"] = "Report"
# Create the plain-text and HTML version of your message
pd.read_csv('tmp.csv').to_html('report_html.html')
html=open('report_html.html').read()
part1=MIMEText("Following are the instances currently running:\n","plain")
part2=MIMEText(html,"html")
message.attach(part1)
message.attach(part2)
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email,password)
server.sendmail(sender_email, receiver_email,
message.as_string())
我对第 1 部分和第 2 部分输出的单独尝试如下:
您使用的 multipart
容器类型错误。 multipart/alternative
容器告诉接收客户端 "here are multiple variants of the same content; display whichever one suits the user's preferences and your technical capabilities." 但您想说 "here are several parts; display all of them, one way or another." 合适的内容类型是 multipart/mixed
或可能 multipart/related
。
我无法弄清楚为什么我的 python 代码无法在同一封电子邮件中附加 HTML table(第 2 部分)和普通句子(第 1 部分)。我试着评论一行 message.attach(part2)
,反之亦然。 message
object.
port = 587 # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "xyz@gmail.com"
receiver_email = ["abc@qwer.com","def@gmail.com"]
password = getpass.getpass()
message = MIMEMultipart("alternative")
message["From"] = sender_email
message["To"] = ", ".join(receiver_email)
message["Subject"] = "Report"
# Create the plain-text and HTML version of your message
pd.read_csv('tmp.csv').to_html('report_html.html')
html=open('report_html.html').read()
part1=MIMEText("Following are the instances currently running:\n","plain")
part2=MIMEText(html,"html")
message.attach(part1)
message.attach(part2)
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email,password)
server.sendmail(sender_email, receiver_email,
message.as_string())
我对第 1 部分和第 2 部分输出的单独尝试如下:
您使用的 multipart
容器类型错误。 multipart/alternative
容器告诉接收客户端 "here are multiple variants of the same content; display whichever one suits the user's preferences and your technical capabilities." 但您想说 "here are several parts; display all of them, one way or another." 合适的内容类型是 multipart/mixed
或可能 multipart/related
。