0

I am trying to send an outlook email with content from a excel file pasted in the message body of outlook email. I have to use smtplib only

I used the code from here shown below

import csv
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
me = '[email protected]'
server = 'internal-server:25'
you = '[email protected]'
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('input.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'] = me
message['To'] = you
server = smtplib.SMTP(server)
server.ehlo()
server.sendmail(me, you, message.as_string())
server.quit()

However, it prints the table as below (without table grid lines and format)

enter image description here

I expect my output to be like as shown below (as a table and not as a image in outlook body)

enter image description here

1 Answer 1

2

You might want to add a border=1 attribute to your table HTML element. Sadly, tabulate doesn't support such a thing. One way to add the border attribute is to skip tabulate.tabulate and write your own table formatter like so:

def html_tabulate(table):
    table_it = iter(table)
    result = []
    result.append("<table border=1>")
    result.append("<thead>")
    headers = next(table_it)
    result.append("<tr><th>" + "</th><th>".join(headers) + "</th></tr>")
    result.append("</thead>")
    for row in table_it:
        result.append("<tr><td>" + "</td><td>".join(row) + "</td></tr>")
    result.append("</table>")
    return "\n".join(result) 

and then use your new function when you create the HTML for your emaill:

html = html.format(table=html_tabulate(data))
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I am encountering another related problem in smtplib text message. would you be interested to help? stackoverflow.com/questions/71709672/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.