python读取mysql数据到邮件正文后发送邮件

python读取mysql表中字段数据到邮件正文,是变成html还是csv文件,最后发送邮件

html是把内容放在邮件正文
csv是把内容最为附件的方式

应该就是一个类似 html 内容的文件,再邮件上显示的时候就是 html 样式。

数据到正文用html,可以参照一下菜鸟教程https://www.runoob.com/python/python-email.html

这个是之前爬股票信息中构造html的一段代码,转换成html后以html形式attach到邮件中,看能否参考

import pandas as pd

name = '20220208'

data = pd.read_excel(name + '.xlsx')

lst = []

# 综合百分比(16) 名称(1) 态度(2) 近期平均成本(3) 技术(6) 资金(8) 消息(10) 行业(12)
# 基本(14) 链接(18)

for i in data.values:
    lst.append([i[16], i[1], i[2], i[3], i[6], i[8], i[10], i[12], i[14], i[18]])

lst.sort(reverse = True)

with open('html_store\\' + name + '.html', 'w') as f:
    f.write('<html>\n')
    f.write('\t<head>\n')
    f.write('\t\t<title>' + name + '</title>\n')
    f.write('\t\t<meta charset = "gbk"/>\n')
    f.write('\t</head>\n')
    f.write('\t<body>\n')
    f.write('\t\t<table border = "1" align = "center">\n')
    f.write('\t\t\t<tr>\n')
    f.write('\t\t\t\t<th>名称</th>\n')
    f.write('\t\t\t\t<th>态度</th>\n')
    f.write('\t\t\t\t<th>近期平均成本</th>\n')
    f.write('\t\t\t\t<th>技术</th>\n')
    f.write('\t\t\t\t<th>资金</th>\n')
    f.write('\t\t\t\t<th>消息</th>\n')
    f.write('\t\t\t\t<th>行业</th>\n')
    f.write('\t\t\t\t<th>基本</th>\n')
    f.write('\t\t\t\t<th>综合</th>\n')
    f.write('\t\t\t</tr>\n')
    for i in lst:
        f.write('\t\t\t<tr>\n')
        f.write('\t\t\t\t<td><a href="{}">{}</a></td>\n'.format(i[9], i[1]))
        f.write('\t\t\t\t<td>{}</td>\n'.format(i[2]))
        f.write('\t\t\t\t<td>{}</td>\n'.format(i[3]))
        f.write('\t\t\t\t<td>{}</td>\n'.format(int(i[4])))
        f.write('\t\t\t\t<td>{}</td>\n'.format(int(i[5])))
        f.write('\t\t\t\t<td>{}</td>\n'.format(int(i[6])))
        f.write('\t\t\t\t<td>{}</td>\n'.format(int(i[7])))
        f.write('\t\t\t\t<td>{}</td>\n'.format(int(i[8])))
        f.write('\t\t\t\t<td>{}</td>\n'.format(int(i[0])))
        f.write('\t\t\t</tr>\n')
    f.write('\t\t</table>\n')
    f.write('\t</body>\n')
    f.write('</html>')

效果是这样

img


基本就是把内容放在html列表里,保存为html格式就行

<table>
    <tr>
        <th>表头</th>
    </tr>
    <tr>
        <td>内容</td>
    </tr>
</table>