Python提取MySQL数据为EXCEL文件后邮件发送

1、代码使用的是Python3.6版本。 

2、重点是解决提取为excel时中文乱码及邮件发送附件名称中文乱码问题。

# -*- coding: UTF-8 -*-
import smtplib
import email.mime.multipart
import email.mime.text
import email.mime.base
import os.path
import pymysql
import xlwt
import time
import base64

#生成excel文件名
v_curr_time = time.strftime('%Y%m%d',time.localtime(time.time()))
v_file_name = '案件导入模板 '+ v_curr_time + '-2-逾期.xls'

#数据库对应地址及用户名密码,指定格式,解决输出中文乱码问题
conn = pymysql.connect(host='xx.x.xx.xxx', port=xxxx, user='xxx', passwd='xxx',db='xxx',charset='utf8')  

#cursor获得python执行Mysql命令的方法,也就是操作游标
cur = conn.cursor() 
v_sql="select * from xxx"
cur.execute(v_sql)

#fetchall()则是接收全部的返回结果行
rows = cur.fetchall()
v_cnt = len(rows)

#生成excel文件
book=xlwt.Workbook()

# 如果对一个单元格重复操作,会引发
# returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0
# 所以在打开时加cell_overwrite_ok=True解决
sheet1=book.add_sheet('Sheet1',cell_overwrite_ok=True)

#表头标题
sheet1.write(0,0,'区')
sheet1.write(0,1,'支付类型')
sheet1.write(0,2,'支付账号')
sheet1.write(0,3,'支付时间')
sheet1.write(0,4,'支付期款')
sheet1.write(0,5,'支付金额')
sheet1.write(0,6,'姓名')
sheet1.write(0,7,'职位')
sheet1.write(0,8,'案件来源')
sheet1.write(0,9,'调查原因')
sheet1.write(0,10,'涉及合同号')

#每一列写入excel文件,不然数据会全在一个单元格中
for i in range(len(rows)):
    for j in range(11):
        #print (rows[i][j])- 
        #print ("--------")
        sheet1.write(i+1,j,rows[i][j])


book.save("D:/"+v_file_name)
cur.close()
conn.close()

#邮件信息
From = "[email protected]"
To = "[email protected]"
file_name = v_file_name

server = smtplib.SMTP("smtp.mail.qq.com")
server.login("xxx","xxx") #仅smtp服务器需要验证时

# 构造MIMEMultipart对象做为根容器
main_msg = email.mime.multipart.MIMEMultipart()

# 构造MIMEText对象做为邮件显示内容并附加到根容器
text_msg = email.mime.text.MIMEText("本日逾期需导入系统数据,请查收,谢谢。")
main_msg.attach(text_msg)

# 构造MIMEBase对象做为文件附件内容并附加到根容器
contype = v_file_name
maintype, subtype = contype.split(' ')

# 读入文件内容并格式化
data = open("D:/"+file_name, 'rb')
file_msg = email.mime.base.MIMEBase(maintype, subtype)
file_msg.set_payload(data.read( ))
data.close( )
email.encoders.encode_base64(file_msg)

# 设置附件头
basename = os.path.basename("D:/"+file_name)
file_msg.add_header('Content-Disposition',
#附件如果有中文会出现乱码问题,加入gbk
 'attachment', filename= ('gbk', '', basename)) 
main_msg.attach(file_msg)

# 设置根容器属性
main_msg['From'] = From
main_msg['To'] = To
main_msg['Subject'] = "案件导入模板-逾期数据"+ v_curr_time
main_msg['Date'] = email.utils.formatdate( )

# 得到格式化后的完整文本
fullText = main_msg.as_string( )

# 用smtp发送邮件
try:
    server.sendmail(From, To, fullText)
    print ("发送成功")
except Exception as e:
        print ("发送失败")
        print (str(e))    
finally:
    server.quit()


你可能感兴趣的:(Python)