How to embed a CSV file into an HTML table inside an email?

Viewed 982

I am using the email package in Python to send out some emails. I am able to send emails with a .csv attachments, but they always appear at the top of the email. I need to embed the attachment in the table, however, but I can't figure out how. I'd like it to look like this: Example email with attachment

Here is the code I'm currently using:

import smtplib
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

msg = MIMEMultipart('alternative')
msg['From'] = 'from@example.com'
msg['To'] = 'to@example.com'
msg['Subject'] = 'Request'

with open('dataexample.csv') as attachment:
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(attachment.read())

# Add header
part.add_header("Content-Disposition", f"attachment; filename= dataexample.csv",)
encoders.encode_base64(part)
msg.attach(part)

# html version of message
html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table {
        border-collapse: collapse;
        }
        table, td {
        border: 1px solid black;
        }
    </style>
</head>
<body>
<table style="width:100%;">
    <tr>
        <td>First Column First Row</b></td>
        <td>Second Column First Row</td>
    </tr>
    <tr>
        <td>First Column Second Row</td>
        <td></td>  # i want the csv file to be embedded in this cell of the table
</table>
</body>
</html>
"""

msg.attach(MIMEText(html, 'html'))
server = smtplib.SMTP(host='host', port=25)
server.send_message(msg)
1 Answers

You can use Pandas to get a HTML string representation of a CSV file:

import pandas as pd

df = pd.read_csv('my.csv', header=None) # change options if needed...
html = df.to_html() # also has lots of nifty options

See pandas.read_csv and pandas.DataFrame.to_html

You can just append that string to whatever else you need for the email.

Related