Jagdish693
Jagdish693

Reputation: 23

Python How to send multiple dataframe as HTML tables in the email body

i've split the single dataframe in to 4 dataframes based on the column value and i want to sent all those dataframes in the email body with proper table formatting, please advise how can i achieve this.

Upvotes: 1

Views: 10145

Answers (2)

Milon Sarker
Milon Sarker

Reputation: 478

Welcome to Stack Overflow. You should ask question after trying by yourself. Lots of help is there on net.

However you may use these below code snippet to send multiple Data Frame as email. Below code is pretty straight forward and hope no explanation is needed.

#!/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 = "[email protected]"
    receiver = ['[email protected]']
    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())

Upvotes: 4

lrh09
lrh09

Reputation: 587

By using 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>

Upvotes: 1

Related Questions