python3+mysql查詢(xún)數(shù)據(jù)并通過(guò)郵件群發(fā)excel附件
本文實(shí)例為大家分享了python3郵件群發(fā)excel附件的具體代碼,供大家參考,具體內(nèi)容如下
連接、查詢(xún)mysql,導(dǎo)入到excel文件,定時(shí)群發(fā)郵件與附件。
主要用到pymysql ,smtplib , xlwt
#1、導(dǎo)入模塊
import pymysql #Python3的mysql模塊,Python2 是mysqldb import os import datetime #定時(shí)發(fā)送,以及日期 import shutil #文件操作 import smtplib #郵件模塊 from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header import time import xlwt #excel寫(xiě)入
#2、連接并查詢(xún)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ù)庫(kù)編碼注意是utf8,不然中文結(jié)果輸出會(huì)亂碼
print("MYSQL CONNECTED.")# 連接數(shù)據(jù)庫(kù)
cursor = db.cursor()# 使用cursor()方法獲取操作游標(biāo)
cursor.execute(sql)# 執(zhí)行SQL語(yǔ)句
print('SQL EXECUTED')
results = cursor.fetchall()# 結(jié)果
return results
print('RESULTS EXECUTED')
db.close() # 關(guān)閉數(shù)據(jù)庫(kù)連接
print('MYSQL CLOSED')
except:
print('SQL FAILED')
#3、寫(xiě)入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') #打開(kāi)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")
#5、配置與執(zhí)行
while True:
#配置
#__time_____
ehour=5#定時(shí)小時(shí)
emin=21#定時(shí)分鐘
esec=41#定時(shí)秒
current_time = time.localtime(time.time()) #當(dāng)前時(shí)間date
cur_time = time.strftime('%H%M', time.localtime(time.time())) #當(dāng)前時(shí)間str
#__mysql_____
mysql_host = mysql_host #登錄host
mysql_port =mysql_port #登錄port
mysql_user = mysql_user #登錄名
mysql_password = mysql_password #登錄密碼
mysql_db = mysql_db #數(shù)據(jù)庫(kù)
sql = sql.encode('utf-8') #sql查詢(xún)語(yǔ)句編碼
#__email_____
sender = sender #發(fā)件人郵箱
receiver = ['453032441@qq.com'] #收件人郵箱,可以多個(gè)(列表形式)群發(fā)
#
username = username #發(fā)件人姓名
password = password #smtp密碼,qq是給你分配一串,163是自己設(shè)置
smtpserver = smtpserver #郵箱服務(wù)器
subject = "Hey,here's something interesting" #郵件標(biāo)題
e_content = '{0:^27}\n{1:^27}\n{2:^25}\n{3:^25}'.format('i','/ \\','(-----)','(--------)') #郵件正文 #郵件正文
#__file_____
file_path = "D:/" #文件位置
file_name="shit.xls" #文件名
fLocate = file_path + file_name #文件路徑
file_subject='Gave', 'you', 'a', 'piece', 'of', 'shit.' #sheet標(biāo)題
file_sheet='ok' #sheet名
style0=xlwt.XFStyle()
style0.num_format_str='YYYY-MM-DD'
#操作
if ((current_time.tm_hour == ehour) and (current_time.tm_min == emin) and (current_time.tm_sec == esec)):
print ("START")
results=eMysql(mysql_host,mysql_port,mysql_user,mysql_password,mysql_db,sql)
eWrite(fLocate, results, file_sheet, file_subject,style0)
eSend(sender, receiver, username, password, smtpserver, subject, e_content, file_path,file_name)
print(cur_time)
time.sleep(1)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python3實(shí)現(xiàn)mysql導(dǎo)出excel的方法
- Python3讀取Excel數(shù)據(jù)存入MySQL的方法
- python實(shí)現(xiàn)讀取excel寫(xiě)入mysql的小工具詳解
- python pymysql庫(kù)的常用操作
- Python pymysql模塊安裝并操作過(guò)程解析
- 使用Python操作MySQL的小技巧
- 使用python把xmind轉(zhuǎn)換成excel測(cè)試用例的實(shí)現(xiàn)代碼
- Python xlrd/xlwt 創(chuàng)建excel文件及常用操作
- python合并多個(gè)excel文件的示例
- python查詢(xún)MySQL將數(shù)據(jù)寫(xiě)入Excel
相關(guān)文章
解決pandas使用read_csv()讀取文件遇到的問(wèn)題
今天小編就為大家分享一篇解決pandas使用read_csv()讀取文件遇到的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
python?flask框架中多種查詢(xún)參數(shù)的獲取方式
這篇文章主要介紹了pythonflask框架的生命周期以及多種查詢(xún)參數(shù)的獲取方式,文章通過(guò)代碼示例和圖文講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-03-03
淺談Series和DataFrame中的sort_index方法
今天小編就為大家分享一篇淺談Series和DataFrame中的sort_index方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
python 在threading中如何處理主進(jìn)程和子線程的關(guān)系
這篇文章主要介紹了python 在threading中如何處理主進(jìn)程和子線程的關(guān)系,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04
python實(shí)現(xiàn)文件名批量替換和內(nèi)容替換
這篇文章主要介紹了python實(shí)現(xiàn)文件名批量替換和內(nèi)容替換,第一個(gè)例子可以指定文件類(lèi)型,需要的朋友可以參考下2014-03-03
python應(yīng)用之如何使用Python發(fā)送通知到微信
現(xiàn)在通過(guò)發(fā)微信信息來(lái)做消息通知和告警已經(jīng)很普遍了,下面這篇文章主要給大家介紹了關(guān)于python應(yīng)用之如何使用Python發(fā)送通知到微信的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03

