前言
一直想把excel附件写成html格式放在正文中,通过各种搜索,并没有发现有一个是自己想要的结果。
大多数教程都是通过pandas中的to_html 转化为HTML格式,但是这个格式真的是太丑了,后来看到大神通过css调整这样的格式
试了一下果真做成了自己想要的结果,记录下来,供大家参考。
若对html 不熟悉的,请进入我的前两篇博客
正文
实现效果如下:
重要代码
这段代码是处理html表格样式的具体实现过程
data ={'col1': [1, 2], 'col2': [3, 4],'col3': ['5', '6'], 'col4': ["7", "8"], 'col5': ["test5", "test5"], 'col6': ["test6", "test6"], 'col7': ["test7", "test7"], 'col8': ["test8", "test8"]}
msg_html_data =pd.DataFrame(data)
msg_html_str= msg_html_data.to_html(header=True, index=False, border=1)
replace_html = """<table class="gridtable" align="center">
<caption><h3>定制邮件发送</h3></caption>
""" # 添加标题
msg_html_str = msg_html_str.replace('<table border="1" class="dataframe">', replace_html) # 替换为指定的格式和标题
msg_html_str = msg_html_str.replace("right", "center ") # 标题居中
msg_html_str = msg_html_str.replace("<th>", '<th><font size="2" color="white">') # 更改颜色和大小
msg_html_str = css_style_01 + msg_html_str.replace("</th>", '</font></th> ') # 添加结束符
下面附上代码:
# -*- coding: utf-8 -*-
# @Time : 2019/8/14 11:09
# @Author : hejipei
# @File : email_test.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email import encoders
import pandas as pd
# css格式设置
css_style_01 = """
<caption> </caption>
<!-- CSS goes in the document HEAD or added to your external stylesheet -->
<style type="text/css">
table.gridtable {
font-family: verdana,arial,sans-serif;
font-size:12px;
color:#333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table.gridtable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #003366;
}
table.gridtable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
</style>
<!-- Table goes in the document BODY -->
<!-- <table class="gridtable"> -->
"""
def sendmail(subject,toaddrs, ccaddrs,fromaddr, smtpaddr, password, msg_txt = None,msg_excel = None,msg_html_table = None):
'''
:param subject: 邮件的主题(标题)
:param toaddrs: 接收人 列表的形式输入
:param ccaddrs: 抄送人 列表的形式输入
:param fromaddr: 发送人
:param smtpaddr: 发送的stmp地址(不同的邮箱有不同的地址,请查询)
:param password: 发送人的授权密码
:param msg: 发送的文本内容
:param msg_txt: 发送的文本内容
:param msg_excel: 发送的附件
:param msg_html_table 发送的html表格
:return: 返回是否发送成功
'''
mail_msg = MIMEMultipart()
mail_msg['Subject'] = subject
mail_msg['From'] = fromaddr
mail_msg['To'] = ','.join(toaddrs)
mail_msg['CC'] = ','.join(ccaddrs)
# 添加文本信息
if msg_txt:
msg_str = "test请查收邮件"
mail_msg.attach(MIMEText(msg_str, 'html', 'utf-8'))
# 添加html表格
if msg_html_table:
data ={'col1': [1, 2], 'col2': [3, 4],'col3': ['5', '6'], 'col4': ["7", "8"], 'col5': ["test5", "test5"], 'col6': ["test6", "test6"], 'col7': ["test7", "test7"], 'col8': ["test8", "test8"]}
msg_html_data =pd.DataFrame(data)
msg_html_str= msg_html_data.to_html(header=True, index=False, border=1)
replace_html = """<table class="gridtable" align="center">
<caption><h3>定制邮件发送</h3></caption>
""" # 添加标题
msg_html_str = msg_html_str.replace('<table border="1" class="dataframe">', replace_html) # 替换为指定的格式和标题
msg_html_str = msg_html_str.replace("right", "center ") # 标题居中
msg_html_str = msg_html_str.replace("<th>", '<th><font size="2" color="white">') # 更改颜色和大小
msg_html_str = css_style_01 + msg_html_str.replace("</th>", '</font></th> ') # 添加结束符
mail_msg.attach(MIMEText(msg_html_str, 'html', 'utf-8'))
# 添加附件excel表格
if msg_excel:
path_file = 'excel_test.xlsx' #附件地址
msg_html_data.to_excel(path_file,index =False)
part = MIMEApplication(open(path_file, 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=path_file)
mail_msg.attach(part)
# 登陆和发送信息
try:
s = smtplib.SMTP()
s.connect(smtpaddr) # 连接smtp服务器
s.login(fromaddr, password) # 登录邮箱
s.sendmail(fromaddr, toaddrs + ccaddrs, mail_msg.as_string()) # 发送邮件
s.quit()
print('邮件发送成功,请查收邮箱。')
except Exception as e:
print("Error: unable to send email")
if __name__ == '__main__':
# 登陆信息
fromaddr = "xxxxxxxx@xxxx.com"
smtpaddr = "smtphm.qiye.163.com"
password = "******"
# 发送信息
subject = "定制邮件主题test"
toaddrs = ["xxxxx@xxxx.com"]
ccaddrs = ["xxxxxxxx@xxxxx.com"]
# 发送邮件
sendmail(subject, toaddrs, ccaddrs, fromaddr, smtpaddr, password, msg_txt = 1,msg_excel = 1,msg_html_table = 1)
有疑问请留言,看到就回复。