pythonpandasdataframesmtplibmimemultipart

email dataframe as table in mail body using python


I am working on a python project where I am needed to send a mail that contains some text and a dataframe. I need the dataframe to be added to the mail body as a table and not an attachment. The dataframe would not have more than 5-6 columns and 10-15 rows. No matter what I try, the dataframe is getting attached as an html file.

I am sorry for any lapses in the format of the question. Thanks in advance. I am using the below code right now :

'''

    from pretty_html_table import build_table
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    import smtplib
    
    
    email_df  = mail_df *(mail_df is the dataframe I need to send)
    
    mail_df.to_string(index=False)
    body1 = '''Dear Employee,

        Please find the below details. 
        Please confirm these entries and incase of any changes needed, Log in to - 
        abcd.com. 
        ''' +'\n\n'
    
    mail_df = mail_df[['IDNo','Value1','Value2','Value3']]

    host = "host.name.com"
    
    
    TO = "pqr@gmail.com"

    msg = MIMEMultipart()
    
    msg['Subject'] = "Mail Subject"
    msg['From'] = 'xyz@gmail.com'
    html = """\
            <html>
                <head></head>
                    <body>
                        {0}
                    </body>
            </html>
    """.format(mail_df.to_html(index=False))

    part1 = MIMEText(html, 'html')
    
    
    msg.attach(part1)


    server = smtplib.SMTP(host)
    server.starttls()
    server.sendmail(msg['From'], TO , msg.as_string())
    server.close()

'''


Solution

  • You could make it much simpler with the EmailMessage interface (around since Python 3.3)

    from email.message import EmailMessage
    import smtplib
    
    # Write the header in HTML
    body1 = '''<p>Dear Employee,</p>
        <p>Please find the below details.<br>
        Please confirm these entries and incase of any changes needed, Log in to abcd.com.</p>
    '''
    
    
    host = "host.name.com"
    
    TO = "pqr@gmail.com"
    
    msg = EmailMessage()
    
    msg['Subject'] = "Mail Subject"
    msg['From'] = 'xyz@gmail.com'
    msg['To'] = TO
    
    # write the header and the table in the same html bloc
    html = """\
            <html>
                <head></head>
                    <body>
                        {0}
                        {1}
                    </body>
            </html>
    """.format(body1, mail_df.to_html(index=False))
    
    # set that html as the content of the message
    msg.set_content(html, subtype='html')
    
    
    server = smtplib.SMTP(host)
    server.starttls()
    
    # and send it...                        
    server.send_message(msg)
    server.close()