I had the same problem. Here is a demo what I did.
The idea is to convert all the csv files to html tables and send them as one html. In this example: there are 3 csv files. I would like to attach csv0.csv as attachment, put csv1.csv and csv2.csv as html tables in email body.
#!/usr/bin/env python
import csv, os
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.MIMEText import MIMEText
import smtplib
import mimetypes
from email import encoders
from email.message import Message
def csv2htmlTableStr(CsvFileName):
# this function is adapted from
# https://stackoverflow.com/questions/36856011/convert-csv-to-a-html-table-format-and-store-in-a-html-file
#
# Open the CSV file for reading
reader = csv.reader(open(CsvFileName))
# initialize rownum variable
rownum = 0
# write <table> tag
HtmlStr = ''
HtmlStr += '<table>'
# generate table contents
for row in reader: # Read a single row from the CSV file
# write header row. assumes first row in csv contains header
if rownum == 0:
HtmlStr += '<tr>' # write <tr> tag
for column in row:
HtmlStr += '<th>' + column + '</th>'
HtmlStr += '</tr>'
#write all other rows
else:
HtmlStr += '<tr>'
for column in row:
HtmlStr += '<td>' + column + '</td>'
HtmlStr += '</tr>'
#increment row count
rownum += 1
# write </table> tag
HtmlStr += '</table>'
# print results to shell
#print "Created " + str(rownum) + " row table."
return HtmlStr
me = "<from email>" # REPLACE THIS
you = '<to email>' # REPLACE THIS
csv0 = "/tmp/csv_as_attachment.csv"
csv1 = "/tmp/csv_as_html_table1.csv"
csv2 = "/tmp/csv_as_html_table2.csv"
ctype, encoding = mimetypes.guess_type(csv0)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
fp = open(csv0)
# Note: we should handle calculating the charset
attachment = MIMEText(fp.read(), _subtype=subtype)
fp.close()
csv1Str = csv2htmlTableStr(csv1)
csv2Str = csv2htmlTableStr(csv2)
text = """
Here is the first table:
""" + csv1Str + """
Here is another table:
""" + csv2Str + """
"""
html = """
<html><body>
<p><b><font color='red'>Here is the first table:</font></b></p>
""" + csv1Str + """</p>
<p><b><font color='red'>Here is another table:</font></b></p>
""" + csv2Str + """</p>
</body></html>
"""
message = MIMEMultipart(
"alternative", None, [MIMEText(text), MIMEText(html,'html')])
message['Subject'] = "Try to embed more than one html tables in email body"
message['From'] = me
message['To'] = you
attachment.add_header("Content-Disposition", "attachment", filename='csv0')
message.attach(attachment)
server = smtplib.SMTP('localhost')
server.sendmail(me, [you], message.as_string())
server.quit()