Nicolas Gutierrez
Nicolas Gutierrez

Reputation: 131

How to keep string formatting when sending an email.message via smtplib?

I am using Python34 to send messages via email. A part of the message is tabular. The column aligment gets all messed up in the email. Here is an illustration of how I am adding tables to the message:

import email.message
import smtplib


rows = [['A','EEEEE','A'],
['BB','DDDD','BB'],
['CCC','CCC','CCC'],
['DDDD','BB','DDDD'],
['EEEEE','A','EEEEE']]

msg_text = ""
for row in rows:
    msg_text += "{:<8}{:<8}{:<8}\n".format(row[0], row[1], row[2])

msg = email.message.Message()
msg['Subject'] = 'Subject'
msg['From'] = 'sender@from'
msg['To'] = 'receiver@to'
msg.add_header('Content-Type','text/plain')
msg.set_payload(msg_text)

smtp_connection = smtplib.SMTP('HHHHUB02', 25, timeout=120)
smtp_connection.sendmail(msg['From'], msg['To'], msg.as_string())

print(msg.as_string())

It looks like this on my terminal: terminal print screen

It looks like this on my email: email print screen

How to keep string formatting when sending an email.message via smtplib?

Upvotes: 0

Views: 4485

Answers (1)

Nicolas Gutierrez
Nicolas Gutierrez

Reputation: 131

(solution) With the code below I was able to combine text and tables in an htlm message that preserved table alignment.

from email.mime.text import MIMEText
import smtplib

html_font_style = 'style="font-size: 13px; font-family: calibri"'

message = '<!DOCTYPE html>\n'
message += '<html>\n'
message += '<body>\n'

text = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \n"
text += "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB \n"
text_html = "<p {}> {} </p>\n".format(html_font_style, text.replace('\n', '\n<br /> '))

table_html = '<table {}>\n'.format(html_font_style)

table_data = [['A','EEEEE','A'],
['BB','DDDD','BB'],
['CCC','CCC','CCC'],
['DDDD','BB','DDDD'],
['EEEEE','A','EEEEE']]
for data in table_data:
    table_html += '  <tr>\n'
    table_html += '    <td> '
    table_html += ' </td> <td> '.join(data)
    table_html += ' </td>'
    table_html += '  </tr>\n'
table_html += '</table>\n'

message = message + text_html + table_html
message += '</body>\n'
message += '</html>\n'

msg = MIMEText(message, 'html')
msg['Subject'] = 'Subject'
msg['From'] = 'sender@from'
msg['To'] = 'receiver@to'

smtp_connection = smtplib.SMTP('HHHHUB02', 25, timeout=120)
smtp_connection.sendmail(msg['From'], msg['To'], msg.as_string())

Upvotes: 2

Related Questions