python邮件发送HTML表格

很多时候需要把表格发送到邮件,HTML格式的则比较好用。
安装html-table包

pip install html-table

使用HTMLTable编辑表格,包括单元格合并,表格样式,单元格样式,表头样式,遍历表格数值,单元格背景色填充,整行背景色填充等等。

#!/usr/bin/env python3
#coding=utf-8
from HTMLTable import HTMLTable
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid
from smtplib import SMTP, SMTP_SSL
from email.mime.multipart import MIMEMultipart

#标题
table = HTMLTable(caption="appale")
#表头,表头分为两行,有些单元格需要合并,被合并的单元格需要留空占位
table.append_header_rows((
  ('地区',  '房价',  '环比',       ''),
  ('',    '',       '增长量',   '增长率'),
))

# 合并单元格
table[0][0].attr.rowspan = 2
table[0][1].attr.rowspan = 2
table[0][2].attr.colspan = 2

# 数据行
table.append_data_rows((
  ('深圳', 11, 1, '10%'),
  ('东莞', 4, -1, '-20%'),
  ('惠州',3, 1, '20%'),
))

# 标题样式
table.caption.set_style({
     
  'font-size': '100px',
})

# 表格样式,即标签样式
table.set_style({
     'border-collapse':'collapse','word-break':'keep-all','white-space':'nowrap','font-size':'14px','width':'100%','height':'200px'})# 统一设置所有单元格样式,
table.set_cell_style({ 'border-color': '#000', 'border-width': '1px', 'border-style': 'solid', 'padding': '5px', }) # 表头样式 table.set_header_row_style({ 'color': '#fff', 'background-color': '#48a6fb', 'font-size': '18px', }) # 覆盖表头单元格字体样式 table.set_header_cell_style({ 'padding': '15px', }) # 调小次表头字体大小 table[1].set_cell_style({ 'padding': '8px', 'font-size': '15px', }) # 遍历数据行,如果增长量为负,单元格背景颜色标红 for row in table.iter_data_rows(): if row[2].value < 0: row[2].set_style({ 'background-color': '#DC143C', }) # 遍历数据行,如果增长量为负,整行背景颜色标绿 for row in table.iter_data_rows(): if row[1].value > 10: row.set_style({ 'background-color': ' #00FF00', }) html_table = table.to_html() print(html_table) context = MIMEText( html_table, _subtype='html', _charset='utf-8') msg = MIMEMultipart() mail_to_list = ["[email protected]"] msg['To'] = ",".join(mail_to_list) msg['From'] = '[email protected]' msg['Subject'] = '日报' msg['Date'] = formatdate(localtime=1) msg['Message-ID'] = make_msgid() msg.attach(context) smtp_server = 'smtp.qq.com' smtp = SMTP(smtp_server) smtp.login('[email protected]', '123456') smtp.sendmail(msg['From'], mail_to_list, msg.as_string()) smtp.quit()

你可能感兴趣的:(python)