0

Python- SMTP customized mail body including Dataframe table and plain text : i am looking to send an email with mail body consisting of plain text like "Dear USer, Below are KPI details:

Data frame Table

when i try to send i am getting Table as attachment .

Yeruva
  • 11
  • 5

1 Answers1

-1

I'm missing some context, so I'll assume that by 'Dataframe', you mean pandas DataFrame and that you're using Python's builtin smtplib.

The following example sends an email message with a Pandas dataframe in its body:

import pandas as pd
import html
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send_email(msg_body):
    # The following block is inspired by Todor Minakov's answer in https://stackoverflow.com/a/33121151/13891613
    sender = "someemailaddress@somehost.someprefix"
    receiver = "someotheremailaddress@someotherhost.someprefix"
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Alert"
    msg['From'] = sender
    msg['To'] = receiver
    msg_body = html.escape(msg_body)
    message_html = f'<html><body><pre>{msg_body}</pre></body></html>'
    part2 = MIMEText(message_html, 'html')
    msg.attach(part2)
    # Send the message via gmail's regular server, over SSL - passwords are being sent, afterall
    s = smtplib.SMTP_SSL('smtp.gmail.com')
    # do the smtp auth; sends ehlo if it hasn't been sent already
    s.login(sender, password=input("Type your password:\n"))
    s.sendmail(sender, receiver, msg.as_string())
    s.quit()


if __name__ == '__main__':
    # Create an example pandas dataframe
    data = {'Column A': ['Some value', 'Some value2', 'Some value3'],
            'Column B': ['Some value', 'Some value2', 'Some value3'],
            'Column C': ['Some value', 'Some value2', 'Some value3'],
            }
    df = pd.DataFrame (data, columns = ['Column A','Column B', 'Column C'])
    
    # Send the dataframe in an email using smtplib
    message = f"Dear User, Below are KPI detail:\n\n{df.to_string()}"
    send_email(message) 

The above script produced the following message in my gmail account (after authenticating my machine against the gmail account):

enter image description here

If by 'Dataframe' you meant something different than the pandas DataFrame, then you can simply serialize your data frame object to a string, and pass it in the message body, similarly to how it's done in the script.

EliranLoi
  • 54
  • 4