python邮件发送:发送csv表格并转成HTML表单形式,添加多收件人与抄送功能

代码:

# 将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

效果:

查看邮箱已发邮件,可看结果

参考链接:https://www.cnblogs.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值