溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python3+mysql查詢數據并通過郵件群發excel附件

發布時間:2020-08-22 20:15:49 來源:腳本之家 閱讀:154 作者:小彌彌子 欄目:開發技術

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

連接、查詢mysql,導入到excel文件,定時群發郵件與附件。
主要用到pymysql ,smtplib , xlwt

#1、導入模塊

import pymysql #Python3的mysql模塊,Python2 是mysqldb
import os
import datetime #定時發送,以及日期
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寫入

#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')#連接數據庫編碼注意是utf8,不然中文結果輸出會亂碼
  print("MYSQL CONNECTED.")# 連接數據庫
  cursor = db.cursor()# 使用cursor()方法獲取操作游標
  cursor.execute(sql)# 執行SQL語句
  print('SQL EXECUTED')
  results = cursor.fetchall()# 結果
  return results
  print('RESULTS EXECUTED')
  db.close() # 關閉數據庫連接
  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標題
   fs.write(0, i, subject[i])

  for i in range(len(results)): #sheet數據,日期列格式為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、發送郵件

def eSend(sender,receiver,username,password,smtpserver,subject,e_content,file_path,file_name):
 try:
#郵件頭
  message = MIMEMultipart()
  message['From'] = sender#發送
  message['To'] = ",".join(receiver)#收件
  message['Subject'] = Header(subject, 'utf-8')
  message.attach(MIMEText(e_content, 'plain', 'utf-8'))# 郵件正文

# 構造附件
  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)

#執行
  smtp = smtplib.SMTP()
  smtp.connect(smtpserver) #連接服務器
  smtp.login(username, password) #登錄
  smtp.sendmail(sender, receiver, message.as_string()) #發送
  smtp.quit()
  print("SEND")
 except:
  print("SEND FAILED")

#5、配置與執行

while True:
#配置
 #__time_____
 ehour=5#定時小時
 emin=21#定時分鐘
 esec=41#定時秒
 current_time = time.localtime(time.time())  #當前時間date
 cur_time = time.strftime('%H%M', time.localtime(time.time()))    #當前時間str
 #__mysql_____
 mysql_host = mysql_host #登錄host
 mysql_port =mysql_port #登錄port
 mysql_user = mysql_user #登錄名
 mysql_password = mysql_password #登錄密碼
 mysql_db = mysql_db #數據庫
 sql = sql.encode('utf-8') #sql查詢語句編碼
 #__email_____
 sender = sender #發件人郵箱
 receiver = ['453032441@qq.com'] #收件人郵箱,可以多個(列表形式)群發
#
 username = username  #發件人姓名
 password = password #smtp密碼,qq是給你分配一串,163是自己設置
 smtpserver = smtpserver #郵箱服務器
 subject = "Hey,here's something interesting"  #郵件標題
 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標題
 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)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女