剛入門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)
?
?
轉載于:https://blog.51cto.com/c1813/2152514