【问题标题】:yagmail adding extra line breaks before pandas DataFrame generated htmlyagmail 在 pandas DataFrame 生成 html 之前添加额外的换行符
【发布时间】:2017-08-17 09:58:28
【问题描述】:

我正在尝试使用本文中详述的方法发送包含 pandas DataFrame 的 yagmail 电子邮件:Python Email in HTML format mimelib

但是,无论我尝试什么,yagmail 在打印 DataFrame 之前都会添加一长串换行符。

我的代码是(我只更改了安装的电子邮件地址):

#--- Addition to original post ---
import pandas as pd
df = pd.DataFrame([[900, 20.0], [500, 21.0]], columns =['Quantity', 'Price'])
#--- Addition to original post ---

import time
import yagmail
yag = yagmail.SMTP(username, password)

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = df.to_html()

yag.send('albalb@gmail.com', "This a reminder call " + time.strftime("%c"), [text,html])

生成的电子邮件正文是:

>Hi!
>How are you?
>Here is the link you wanted:
>https://www.python.org
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>   Quantity    Price
>0  900     20.0
>1  500     21.0

我也尝试添加一个 DOCTYPE 标签,编码为 utf-8,从 unicode 转换为字符串,但没有成功。

这是一个错误,或者任何人都可以帮助我解决问题?

编辑#1: 请注意,html 变量包含以下内容:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Quantity</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>900</td>
      <td>20.0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>500</td>
      <td>21.0</td>
    </tr>
  </tbody>
</table>

编辑#2: 为了详细说明我尝试添加 html 和 doctype 标签,我尝试在 html 的开头和结尾添加以下内容。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title>Title</title>
</head>
<body>
...
</body>
</html>

我验证这是有效的 html here 并且生成的电子邮件正文相似。

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

























    Quantity    Price
0   900     20.0
1   500     21.0

【问题讨论】:

  • [text,html] 更改为[html,text] 时的输出是什么。我问的原因是检查df是问题还是yagmail。不幸的是,我看到前面有很多试验和错误!
  • @MattR 谢谢你的建议。我重新运行代码,将最后一行替换为:yag.send('albalb@gmail.com', "This a reminder call " + time.strftime("%c"), [html])。生成的电子邮件正文包含一系列换行符,然后是底部的 html 表格
  • yagmail 的作者在这里....这绝对是一个错误。我可以看到添加了 5 个&lt;br&gt; 标签。我一无所知。
  • @PascalvKooten 谢谢你帮我看这个。你想让我把它添加到某处的错误日志中吗?如果是这样,您可以发布链接吗?
  • @CurryPy 谢谢,我试图找到一个临时解决方案,但找不到。 github.com/kootenpv/yagmail/issues

标签: python html email pandas yagmail


【解决方案1】:

评论太长:您可以做的一件事是在发送和手动删除空格之前创建输出变量。例如,在我过去构建的一个电子邮件程序中,我使用easygui 并使用textbox 为用户创建他们的消息。然后发送该消息。我的小例子:

import easygui as e
text_mes= e.textbox("Add to the Email", "Create Your Email", html)
yag.send('albalb@gmail.com', "This a reminder call " + time.strftime("%c"), [text,text_mes])

这将允许您手动删除行,直到您找到一种方法来创建一些代码来消除空格。

【讨论】:

  • 感谢您抽出宝贵时间帮助我。我修改了帖子以显示 html 变量:它看起来很干净。所以没有什么可以删除的。 html 变量是 unicode,所以我尝试在 yagmail 之前转换为字符串并添加 .encode('utf-8'),但所有变体都会产生相同的结果。我还尝试从表格标签中删除边框和类标识符。
猜你喜欢
  • 2014-03-01
  • 1970-01-01
  • 2018-01-22
  • 2021-06-24
  • 2017-04-05
  • 1970-01-01
  • 2019-08-08
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多