python生成CSV文件并发送邮件

一、前言

  在日常运维的过程中,执行脚本,生成excel报表并发送邮件到邮箱是不可避免的,python生成excel的库有很多,这里选择生成csv格式,因为python内置,不需要额外安装模块,而且使用简单。

二、生产CSV代码

# encoding: utf-8
import codecs
import csv
import datetime

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
def to_csv(datas, env):
    headers = ['ip', u'操作系统', u'分区属性', u'输出返回', u'执行结果']
    # newline=''避免出现空行
    today = datetime.date.today()
    filename = "{}-{}.csv".format(env, today)
    try:
        with open(filename, 'wb') as f:
            f.write(codecs.BOM_UTF8)
            # 标头在这里传入,作为第一行数据
            writer = csv.DictWriter(f, headers)
            writer.writeheader()
            writer.writerows(datas)
    except Exception as e:
        print (u'写入csv错误:' + str(e))
    finally:
        return filename


if __name__ == '__main__':
    data = [{"ip": "192.168.1.2", u'操作系统': "LINUX", u'分区属性': u"x86物理机", u'输出返回': "ok", u'执行结果': u"成功"},
            {"ip": "192.168.1.3", u'操作系统': "LINUX", u'分区属性': u"x86物理机", u'输出返回': "error:xxxxxxxxxxx", u'执行结果': u"成功"},
            {"ip": "192.168.1.4", u'操作系统': "LINUX", u'分区属性': u"x86虚拟机", u'输出返回': "ok", u'执行结果': u"成功"},
            {"ip": "192.168.1.5", u'操作系统': "LINUX", u'分区属性': u"x86虚拟机", u'输出返回': "ok", u'执行结果': u"成功"}]
    env = "dev"
    to_csv(data, env)

生成的文件:

 

 

二、发送邮件代码

from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(filename):
    # 发送邮箱服务器
    smtpserver = 'xx.xx.xx.xx'
    # 发送邮箱用户名密码
    user = 'xxxxxxx@xx.com.cn'
    password = '5tgb^YHN'
    # 发送和接收邮箱
    receives = ['xxxxx@xxx.com.cn']

    msg = MIMEMultipart()  # 创建一个带附件的实例
    subject = Header("xxxxxx执行结果", 'utf-8').encode()
    msg["Subject"] = subject  # 指定邮件主题
    msg["From"] = user  # 邮件发送人
    msg["To"] = ','.join(receives)  # 邮件接收人,如果存在多个收件人,可用join连接
    msg.attach(MIMEText('附件为xxxxx执行结果,请查收!', _subtype='html', _charset='utf-8'))
    part = MIMEApplication(open(filename, 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename=filename)
    msg.attach(part)

    try:
        s = smtplib.SMTP(smtpserver, timeout=10)  # 连接smtp邮件服务器,端口默认是25
        s.login(user, password)  # 登陆服务器
        s.sendmail(user, receives, msg.as_string())  # 发送邮件
        s.close()
    except Exception as e:
        print ("send email error:"+str(e))

 

posted @ 2020-03-17 16:23  HuTiger  阅读(2681)  评论(0编辑  收藏  举报