国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python3+mysql查詢數(shù)據(jù)并通過郵件群發(fā)excel附件

2020-02-22 23:19:05
字體:
供稿:網(wǎng)友

本文實例為大家分享了python3郵件群發(fā)excel附件的具體代碼,供大家參考,具體內(nèi)容如下

連接、查詢mysql,導(dǎo)入到excel文件,定時群發(fā)郵件與附件。
主要用到pymysql ,smtplib , xlwt

#1、導(dǎo)入模塊

import pymysql #Python3的mysql模塊,Python2 是mysqldbimport osimport datetime #定時發(fā)送,以及日期import shutil #文件操作import smtplib #郵件模塊from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.header import Headerimport timeimport xlwt #excel寫入

#2、連接并查詢mysql

def eMysql(mysql_host,mysql_port,mysql_user,mysql_password,mysql_db,sql): try:  db = pymysql.connect(host=mysql_host,port=mysql_port,user=mysql_user, password=mysql_password, db=mysql_db,charset = 'utf8')#連接數(shù)據(jù)庫編碼注意是utf8,不然中文結(jié)果輸出會亂碼  print("MYSQL CONNECTED.")# 連接數(shù)據(jù)庫  cursor = db.cursor()# 使用cursor()方法獲取操作游標(biāo)  cursor.execute(sql)# 執(zhí)行SQL語句  print('SQL EXECUTED')  results = cursor.fetchall()# 結(jié)果  return results  print('RESULTS EXECUTED')  db.close() # 關(guān)閉數(shù)據(jù)庫連接  print('MYSQL CLOSED') except:  print('SQL FAILED')

#3、寫入excel

def eWrite(fLocate,results,file_sheet,file_subject,style0): try:  if os.path.exists(fLocate):   os.remove(fLocate) # 如果文件存在,則刪除  f = xlwt.Workbook(encoding='utf-8') #打開excel文件  fs = f.add_sheet(file_sheet) #sheet名  subject = list(file_subject) #列表化  for i in range(len(subject)): #找到日期列   if '日期' in subject[i]:    col_num=i  for i in range(len(subject)): #sheet標(biāo)題   fs.write(0, i, subject[i])  for i in range(len(results)): #sheet數(shù)據(jù),日期列格式為date   for j in range(len(results[0])):    if j== col_num:     fs.write(i + 1, j, results[i][j],style0)    else:     fs.write(i + 1, j, results[i][j])  for i in range(10): #單元格寬度為   fs.col(i).width=3333  print("WRITE FINISHED")  f.save(fLocate) except :  print ("WRITE FAILED")

#4、發(fā)送郵件

def eSend(sender,receiver,username,password,smtpserver,subject,e_content,file_path,file_name): try:#郵件頭  message = MIMEMultipart()  message['From'] = sender#發(fā)送  message['To'] = ",".join(receiver)#收件  message['Subject'] = Header(subject, 'utf-8')  message.attach(MIMEText(e_content, 'plain', 'utf-8'))# 郵件正文# 構(gòu)造附件  att1 = MIMEText(open(file_path+file_name,'rb').read(), 'base64', 'utf-8')  att1["Content-Type"] = 'application/octet-stream'  att1["Content-Disposition"] = "attachment;filename="+file_name  message.attach(att1)#執(zhí)行  smtp = smtplib.SMTP()  smtp.connect(smtpserver) #連接服務(wù)器  smtp.login(username, password) #登錄  smtp.sendmail(sender, receiver, message.as_string()) #發(fā)送  smtp.quit()  print("SEND") except:  print("SEND FAILED")            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 行唐县| 桦川县| 临西县| 公安县| 高邑县| 临城县| 阜新| 沈丘县| 肇庆市| 河津市| 绍兴市| 大洼县| 潜江市| 拉萨市| 综艺| 台东市| 囊谦县| 肃宁县| 祁连县| 枣强县| 修水县| 禹城市| 株洲县| 光山县| 太谷县| 新乐市| 彭州市| 甘洛县| 山阳县| 黑山县| 如皋市| 徐汇区| 淳安县| 桃园市| 广州市| 子洲县| 达日县| 曲靖市| 余江县| 东兰县| 邵阳市|