Python如何在电子邮件正文中以HTML表格形式发送多个数据框

时间:2019-05-19 13:58:20

标签: python pandas email dataframe

我已根据列值将单个数据帧分为4个数据帧,我想以适当的表格格式发送电子邮件正文中的所有这些数据帧,请告知我该如何实现。

2 个答案:

答案 0 :(得分:1)

通过使用df.to_html()

df = 

   A  B
0  A  C
1  A  G
2  T  T
3  C  G
4  A  A
5  G  G

> print(df.to_html())


<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>A</td>
      <td>C</td>
    </tr>
    <tr>
      <th>1</th>
      <td>A</td>
      <td>G</td>
    </tr>
    <tr>
      <th>2</th>
      <td>T</td>
      <td>T</td>
    </tr>
    <tr>
      <th>3</th>
      <td>C</td>
      <td>G</td>
    </tr>
    <tr>
      <th>4</th>
      <td>A</td>
      <td>A</td>
    </tr>
    <tr>
      <th>5</th>
      <td>G</td>
      <td>G</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:0)

欢迎使用堆栈溢出。自己尝试后应该问问题。网络上有很多帮助。

但是,您可以使用下面的这些代码片段将多个数据框作为电子邮件发送。 下面的代码很简单,希望不需要解释。

#!/usr/local/bin/python3.6
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import pandas as pd
import matplotlib

def send_mail(cdf):
    df = cdf  # Make anaother DF; in you case you'll may be pass another Data Frame to this function
    sender = "xxx@yy.com"
    receiver = ['xxxx@yy.com']
    msg = MIMEMultipart('related')

    msg['Subject'] = "Subject Here"
    msg['From'] = sender
    msg['To'] = ", ".join(receiver)
    html = """\
    <html>
      <head></head>
      <body>
        <p>Hi!<br>
           Here is first Data Frame data:<br>
           {0}
           <br>Here is second Data Frame data:<br>
           {1}

           Regards,
        </p>
      </body>
    </html>

    """.format(cdf.to_html(), df.to_html())

    partHTML = MIMEText(html, 'html')
    msg.attach(partHTML)
    ser = smtplib.SMTP('gateway_server', port_number)
    ser.login("username", "password")
    ser.sendmail(sender, receiver, msg.as_string())