代码:
# 将csv转成html表单并发送html内容的邮件,带抄送功能
import smtplib, time
from email.header import Header
from email.mime.text import MIMEText
import pandas as pd
def csv_to_html():
upload_path = 'total_data.csv'
df = pd.read_csv(upload_path, encoding="utf-8",names=["A","B","C","D","E","F","G","H","I","J","K","L"])
print(df.to_html())
filename = "total_data.html"
with open(filename, 'w') as file_object:
file_object.write(df.to_html())
def send_mail_html(file):
'''发送html内容邮件'''
# 发送邮箱
sender = 'xxx@126.com'
# 接收邮箱
receiver1 = 'xxx@qq.com'
# 抄送邮箱
receiver2 = ",xxx@163.comxxxxx@yy.cn"
receiver = receiver1 + receiver2
# 发送邮件主题
t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
subject = '测试邮件发送_' + t
# 发送邮箱服务器
smtpserver = 'smtp.126.com'
# 发送邮箱用户/密码
username = 'xxxx@126.com'
password = 'xxxxxx'
# 读取html文件内容
f = open(file, 'rb')
mail_body = f.read()
f.close()
# 组装邮件内容和标题,中文需参数‘utf-8’或'GB2312',单字节字符不需要
msg = MIMEText(mail_body, _subtype='html', _charset='GB2312')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
#定义接收邮箱
msg['To'] = receiver1
#定义抄送邮箱
msg['Cc'] = receiver2
# 登录并发送邮件
try:
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver.split(","), msg.as_string())
except Exception as E:
print("邮件发送失败!", str(E))
else:
print("邮件发送成功!")
finally:
smtp.quit()
if __name__ == '__main__':
csv_to_html() #csv转html表单
file = './total_data.html' # 指定文件目录
send_mail_html(file) # 发送html内容邮件
注意:
1 发送邮箱要开通smtp服务
2 pandas库依赖numpy,gcc等,通过 pip3安装
3 python3默认安装pip3,找不到则利用 whereis pip3查看路径,若有多个python,同理也可以使用whereis命令
4邮箱之间用逗号隔开,发送时split
效果:
查看邮箱已发邮件,可看结果