Python驱动的Emai中的HTML和文本

2024-04-20 08:07:45 发布

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

我正在使用MIMEMultipart从Python发送电子邮件。代码如下:

sender = "EMAIL"
recipients = ["EMAIL"]
msg = MIMEMultipart('alternative')
msg['Subject'] = "Subject Text"
msg['From'] = sender
msg['To'] = ", ".join(recipients)

html = PandasDataFrame.to_html()
part2 = MIMEText(html, 'html')
msg.attach(part2)

SERVER = "SERVER"
server = smtplib.SMTP(SERVER)
server.sendmail(sender, recipients, msg.as_string())
server.quit()  

这将Python Pandas数据帧作为HTML插入,工作正常。是否可以在邮件正文中添加脚注作为文本?这两种方法的代码是如何工作的?或者,我可以添加注释作为HTML,但更多的不需要一些脚注添加到电子邮件正文。在

谢谢


Tags: 代码textserver电子邮件emailhtmlmsgsender
2条回答

所以下面的内容不起作用,请看the correct answer

也许是这个?在

html = pd.DataFrame([[1,2,3], ['dog', 'cat', 42]]).to_html()
part1 = MIMEText(html, 'html')
msg.attach(part1)
part2 = MIMEText('html')
coolstring = 'This is a dope-ass DataFrame yo'
part2.set_payload(coolstring)
msg.attach(part2)

虽然我觉得这太像下面的2了。输出如下:

^{pr2}$

找到了两种查看the examples的方法,并将MIMEMultipart上的方法通过dir(MIMEMultipart)的等价物列出

您必须测试三个猜测:

1)你可以通过

msg.epilogue = 'This is a dope-ass DataFrame yo' 

但不确定这是否会出现在电子邮件正文中。在

2)创建另一个MIMEText并附加它。在示例中,这似乎是他们如何完成一次发送大量图片的方式,因此这可能是您的最佳选择。可能应该以这个为首。在

part_text = MIMEText('This is some text, yessir')
msg.attach(part_text)

它看起来有点像是到了那里,因为边界划分是一样的。在

>> print msg.as_string()
Content-Type: multipart/alternative; boundary="===============1672307235=="
MIME-Version: 1.0
Subject: Subject Text
From: EMAIL
To: EMAIL
 ===============1672307235==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<table border="1" class="dataframe">
  # ...DataFrame in HTML here...
</table>
 ===============1672307235==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
This is some text, yessir
 ===============1672307235== 

3)由于要在server.sendmail(sender, recipients, msg.as_string())中实际发送它,您可以将msg转换为字符串,所以您的另一个选择是直接将一些HTML文本手动添加到msg.as_string()中。有点像

msg.as_string().replace('</table>', '</table>\n<p>...your text here</p>')

会很乱,但应该有用。在

让我知道这些是否有帮助!我有点在暗中射击,因为我现在不能测试它。祝你好运!在

此代码起作用:

首先,导入:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication #Used for attachments
import smtplib

代码:

^{pr2}$

如果您还想将文件附加到电子邮件,请使用以下代码

ATTACHMENT_PATH = 'path\\file.type'
with open(ATTACHMENT_PATH, 'r') as fileobj:
    attachment = MIMEApplication(fileobj.read(), Name='file.type')
attachment['Content-Disposition'] = 'attachment; filename="file.type"'
msg.attach(attachment)

以及使用服务器发送的代码

SERVER = "SERVER"
server = smtplib.SMTP(SERVER)
server.sendmail(sender, recipients, msg.as_string())
server.quit()  

相关问题 更多 >