gpt4 book ai didi

HTML 格式的 Python 电子邮件 mimelib

转载 作者:行者123 更新时间:2023-11-30 23:04:34 26 4
gpt4 key购买 nike

我正在尝试在从 python 脚本发送的电子邮件中以 html 格式发送在 Pandas Python 中创建的两个数据帧。

我想编写一个文本和表格,并对另外两个数据帧重复此操作,但脚本无法附加多个 html block 。代码如下:

import numpy as np
import pandas as pd
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

sender = "blabla@gmail.com"
recipients = ['albalb@gmail.com']
msg = MIMEMultipart('alternative')
msg['Subject'] = "This a reminder call " + time.strftime("%c")
msg['From'] = sender
msg['To'] = ", ".join(recipients)

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = df[['SYMBOL','ARBITRAGE BASIS %']].to_html()

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

username = 'blabla@gmail.com'
password = 'blahblah'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(sender, recipients, msg.as_string())
server.quit()
print("Success")

我收到一封电子邮件,其中最后一部分是电子邮件正文中的格式化 html 表格。第 1 部分的文本未出现。怎么了?

最佳答案

问题是您将部件标记为multipart/alternative - 这意味着,“我有多个渲染中的信息;选择您喜欢的一个”,并且您的电子邮件客户端显然是设置选择 HTML 版本。事实上,这两个部分都在那里,但您已将它们标记为“任一/或”,显然您想要两者。

传统的快速解决方法是切换到multipart/lated,但实际上,仅表示内容在其他地方的文本部分的目的是什么?

如果您希望将 HTML 作为附件,还可以为 HTML 部分设置 Content-Disposition:attachment(并提供文件名)。

关于HTML 格式的 Python 电子邮件 mimelib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627662/

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