读取数据库并写入excel表中 发送邮件


'''
写一个函数 实现 传人表名 就导出到excel 如果这一行数据有乱码 就不写到excel里面
然后把excel 当作附件发到邮箱
'''
import pymysql,xlwt,yagmail
def my_db(sql):
import pymysql
coon =pymysql.connect(
host='192.168.1.1',user='xxx',password='123456',
port=3306,db='xxx',charset='utf8',autocommit=True)
cur = coon.cursor()
coon.cursor()
cur.execute(sql)
if sql.strip()[:6].upper()=='SELECT': #去掉前面空格 取sql到开头 然后转换成大写
res=cur.fetchall()
else:
coon.commit()
res='ok'
cur.close()
coon.close()
return res

def export(excel_name):
sql='select * from niea;'
data=my_db(sql) #运行数据库
print(data)
book=xlwt.Workbook() #新建excel
sheet=book.add_sheet('sheet1') #新建sheet页
title=['编号','账户名','密码'] #表头
col =0 #列
for t in title:
sheet.write(0,col,t)
col+=1
row=1 #行数
for d in data: #控制行数
col = 0
for line in d:#控制列数
sheet.write(row,col,line)
col+=1 #循环一次列加1
row+=1
book.save(excel_name)
export('stu.xls')

username='xxxx@163.com'
passwd='xxxxx' #邮箱发送授权码
mail=yagmail.SMTP(user=username,password=passwd,host='smtp.163.com')#连接上邮箱
#安全协议 smtp_ssl=True 如果是QQ邮箱 需要加上
mail.send(to=['xxxxxxx@qq.com','xxxxxxxx@qq.com'],
cc=['kxxxxxxxxxi@163.com'],
subject='邮件主题',
contents='正文内容!',
attachments=r'/Users/hecom/Desktop/自动化st/my_python/day6/stu.xls' #附件文件路径
)

原文地址:https://www.cnblogs.com/niel/p/9336928.html