本文實例為大家分享了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")
新聞熱點
疑難解答
圖片精選