2017-08-07 73 views
-1

我正在使用Python34通過電子郵件發送消息。消息的一部分是表格。列對齊全部混淆在電子郵件中。下面是一個說明如何,我添加表的消息:如何通過smtplib發送email.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'] = '[email protected]' 
msg['To'] = '[email protected]' 
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()) 

它看起來像這樣我的終端上: terminal print screen

它看起來像這樣在我的郵箱: email print screen

如何通過smtplib發送email.message時保持字符串格式?

+0

的可能的複製[如何通過電子郵件在python發送正確的表?](https://stackoverflow.com/questions/43568771/how-to-send-correctly-a-table-by-email -in-python) – stovfl

+0

感謝您分享該鏈接。該解決方案雖然不太合適,但需要進行重大改變。首先,它需要目前不是我們分銷的一部分的表格軟件包。其次,它需要重構我們的代碼,因爲消息只是部分列表(已經更新了我的問題以突出這一事實)。 –

+0

也許你需要將你的內容類型改爲html並指定一個等寬字體。 – khelwood

回答

0

解決方案) 通過下面的代碼,我能夠在保存表對齊的htlm消息中組合文本和表。

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'] = '[email protected]' 
msg['To'] = '[email protected]' 

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