Python 提取数据库(Postgresql)并邮件发送
刚入门python,发现确实是一个不错的语言。
业务部门要求将将某一个数据库中的表,定期发送到相关部门人员邮箱。
其实整个业务需求很简单,实现起来也不难。
但是由于刚入门python,所以还是借鉴了不上网上的内容,也得到了许多群友的提醒。
业务部门使用的是Postgresql数据库,所以使用 了psyconpg2的模块。
整个脚本分为三部分:
1.数据库的连接及数据写入excel表中(整个对新手来说,应该是难点)
2.邮件的发送
3.生成excel文件的删除
# coding: utf-8
import sys
import xlwt
import psycopg2
import datetime
import time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os.path
# 连接数据库的参数:主机,用户,密码,端口及数据库名称
host = '192.168.1.77'
user = 'postgres'
pwd = 'postgres'
port = 5432
db = 'pytest'
sheet_name = 'report' + time.strftime("%Y-%m-%d")
filename = 'report_' + time.strftime("%Y-%m-%d" + "-" + "%H%M%S") + '.xls'
out_path = "d:/test/report_" + time.strftime("%Y-%m-%d" + "-" + "%H%M%S") + ".xls" # 路径文件名使用日期时间来命名,但是文件命名不支持冒号:所以去掉冒号
cur_path = 'd:/test'
print(out_path)
sql = 'select * from website;'
def export():
# 数据库连接
conn = psycopg2.connect(dbname=db, user=user, password=pwd, host=host, port=port)
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()
count = cursor.rowcount
print("Select " + str(count) + " Records")
# cursor.scroll(0, mode='relative')
fields = cursor.description # 数据表的标题
workbook = xlwt.Workbook(encoding='utf-8') # 创建excel文档
sheet = workbook.add_sheet(sheet_name, cell_overwrite_ok=True) # 根据sheet_name 创建excel文档的sheet
for field in range(1, len(fields)): # 写入数据表的文件头
sheet.write(0, field, fields[field][0])
# 逐行逐列的添加数据
for row in range(1, len(result) + 1):
for col in range(0, len(fields)):
sheet.write(row, col, u'%s'%result[row-1][col])
workbook.save(out_path) # 按照out_path的格式和路径保存excel表格
_user = "user1@abc.com"
_pwd = "123456."
areceiver = "user2@163.com"
acc = "user1@abc.com"
# 如名字所示Multipart就是多个部分
msg = MIMEMultipart()
msg["Subject"] = u'[Data Select_' + time.strftime("%Y-%m-%d") + u']'
msg["From"] = _user
msg["To"] = areceiver
msg["Cc"] = acc
def send_email():
conn = psycopg2.connect(dbname=db, user=user, password=pwd, host=host, port=port)
cursor = conn.cursor()
cursor.execute(sql)
cursor.fetchall()
count = cursor.rowcount # summary rows number
# ----这是文字部分-----
content = '''Dear All, \n 附件是每日统计情况,请查收!
总计结果数位:''' + str(count)
part = MIMEText(content, 'plain', 'utf-8')
msg.attach(part)
if count > 0:
# 这是附件部分
# xls类型附件
file_name = 'd:/test/' + filename
part = MIMEText(open(file_name, 'rb').read(), 'base64', 'gb2312')
part["Content-Type"] = 'application/octet-stream'
basename = os.path.basename(file_name)
# part["Content-Disposition"] = 'attachment; filename=%s' % basename.encode('utf-8')
part['Content-Disposition'] = 'attachment; filename=%s' % basename
# part.add_header('Content-Disposition', 'attachment', filename=('utf-8', basename))
msg.attach(part)
s = smtplib.SMTP('mail.ucinbox.com', timeout=120) # 连接smtp邮件服务器
s.login(_user, _pwd)
s.sendmail(_user, areceiver.split(',') + acc.split(','), msg.as_string()) # send mail
print("Email send successfully")
s.close()
else:
print("nothing to send!")
# 删除生成的excel文件
# 之前使用的是将不同的excel放入不同的文件夹,所以写了遍历删除所有excel
def delete(path):
ls = os.listdir(cur_path)
for l in ls:
path_file = os.path.join(path,l) # 取文件路径
if os.path.isfile(path_file):
os.remove(path_file)
else:
for f in os.listdir(path_file):
path_file2 = os.path.join(path_file,f)
if os.path.isfile(path_file2):
os.remove(path_file2)
# 调用函数
if __name__ == "__main__":
export()
send_email()
delete(cur_path)