Add borders of table sent by email via Python

11,326

Solution 1

Here is the full solution of creating the table with borders.

table = '' 
with open('result.csv') as csvFile: 
    reader = csv.DictReader(csvFile, delimiter=',')    
    table = '<tr>{}</tr>'.format(''.join(['<td class="cell">{}</td>'.format(header) for header in reader.fieldnames])) 
    for row in reader:  
        table_row = '<tr>' 
        for fn in reader.fieldnames:            
            table_row += '<td class="cell">{}</td>'.format(row[fn]) 
        table_row += '</tr>' 
        table += table_row


html = """
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>html title</title>
<style type="text/css" media="screen">
table{
    background-color: #000000;
    empty-cells:hide;
  Border:5px solid red;
 }
 td.cell{
    background-color: white;
 }

</style>
</head>
<html><body><p>Hi!</p>
<p>Here is your data.</p>
<table style="border: black 0.5px;"> 
%s 
</table>
<p>Regards,</p>
<p>Python 3.5</p>
</body></html>""" % table


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


message['Subject'] = "Some stats via mail"
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")

Solution 2

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>
"""
Share:
11,326
Anastasia Manokhina
Author by

Anastasia Manokhina

Updated on June 13, 2022

Comments

  • Anastasia Manokhina
    Anastasia Manokhina almost 2 years

    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.

  • Anastasia Manokhina
    Anastasia Manokhina over 6 years
    Thank you! But cat I somehow load the table from csv, not writing explicitly the content of every single cell?
  • Muhammad Ali
    Muhammad Ali over 6 years
    Did not get !! you want to add the content values from CSV ?? mean values in table cells ?? if that you can ,
  • Muhammad Ali
    Muhammad Ali over 6 years
    Reading Data From CSV use that my_data = genfromtxt('my_file.csv', delimiter=',')
  • Anastasia Manokhina
    Anastasia Manokhina over 6 years
    If you suppose numpy.genfromtxt, it doesn't work. Although, I don't know what part exactly you wanted to replace with that code.
  • Muhammad Ali
    Muhammad Ali over 6 years
    It giving any error or what ?? can you share the code how you reading CSV File
  • Anastasia Manokhina
    Anastasia Manokhina over 6 years
    np.genfromtxt('result.csv', delimiter=';') gives array([ nan, nan]). The csv file is same as before.
  • Muhammad Ali
    Muhammad Ali over 6 years
    import csv table = '' with open(csv_path, encoding="utf8") as csvFile: reader = csv.DictReader(csvFile, delimiter=',') table = '<tr>{}</tr>'.format(''.join(['<td>{}</td>'.format(header) for header in reader.fieldnames])) for row in reader: table_row = '<tr>' for fn in reader.fieldnames: table_row += '<td>{}<\td>'.format(row[fn]) table_row += '<\tr>' table += table_row
  • Anastasia Manokhina
    Anastasia Manokhina over 6 years
  • Muhammad Ali
    Muhammad Ali over 6 years
    I am new here , and i think we can not chat , for chat we need REPUTATION100