Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add borders of table sent by email via Python

Currently I use this solution Send table as an email body (not attachment ) in Python for sending tables in emails via Python:

import smtplib
from smtplib import SMTPException
import csv
from tabulate import tabulate

text = """
Hello, Friend.

Here is your data:

{table}

Regards,

Me"""

html = """
<html><body><p>Hello, Friend.</p>
<p>Here is your data:</p>
{table}
<p>Regards,</p>
<p>Me</p>
</body></html>
"""

with open('result.csv') as input_file:
    reader = csv.reader(input_file)
    data = list(reader)

text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))
html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))

message = MIMEMultipart(
    "alternative", None, [MIMEText(text), MIMEText(html,'html')])

message['Subject'] = "Your data"
message['From'] = '[email protected]'
message['To'] = '[email protected]'

sender = "[email protected]"
receivers = ['[email protected]']

try:
    smtp_obj = smtplib.SMTP('mail.abc.com')
    smtp_obj.sendmail(sender, receivers, message.as_string())         
    print ("Successfully sent email")
except SMTPException:
    print ("Error: unable to send email")

Data is loaded from csv file. But I need to add borders to the table to make it look like pandas DataFrame.

like image 223
Anastasia Manokhina Avatar asked Dec 12 '25 04:12

Anastasia Manokhina


1 Answers

Add style to the original html script will work.

html = """
<html>
<head>
<style> 
  table, th, td {{ border: 1px solid black; border-collapse: collapse; }}
  th, td {{ padding: 5px; }}
</style>
</head>
<body><p>Hello, Friend.</p>
<p>Here is your data:</p>
{table}
<p>Regards,</p>
<p>Me</p>
</body></html>
"""
like image 191
Bohan Zhang Avatar answered Dec 13 '25 16:12

Bohan Zhang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!