python3自動發送郵件並添加附件

思路

  1. 從數據庫讀取報表數據
  2. 將報表數據以excel形式存到本地
  3. 將本地報表文件以附件形式添加到郵件發送
  4. 設置定時任務

代碼 

import pymysql
import pandas as pd
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication 
import datetime
import schedule,time

def create_report(host,port,user,passwd,db,sql,annex_path):
    '從數據庫讀取報表數據,以excel形式將報表存到本地'
    conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)# 連接mysql
    cursor = conn.cursor()#創建遊標
    cursor.execute(sql)#執行sql語句
    result = cursor.fetchall()#獲取執行結果    
    result=[list(x) for x in result]
    col_result = cursor.description  # 獲取查詢結果的字段描述
    columns=[x[0] for x in col_result]
    data=pd.DataFrame(result,columns=columns)
    data.to_excel(annex_path,index=False)
    cursor.close()#關閉遊標
    conn.close()#關閉連接

def send_email(file_name,annex_path):
    '#創建報表和發送郵件'  
    try:
        file_name_new=str(datetime.datetime.now().date())+file_name#根據當前日期拼接附件名稱
        annex_path_new=annex_path+'/'+file_name_new  #拼接報表存儲完整路徑 
        create_report(host,port,user,passwd,db,sql,annex_path_new)#創建報表
        
        #傳入郵件發送者、接受者、抄送者郵箱以及主題    
        message = MIMEMultipart()
        message['From'] = sender
        message['To'] = ','.join(receiver)
        message['Cc'] = ";".join(Cc_receiver)
        message['Subject'] = Header(str(datetime.datetime.now().date())+title, 'utf-8')
        
        #添加郵件內容
        text_content = MIMEText(content)
        message.attach(text_content)
        
        #添加附件    
        annex = MIMEApplication(open(annex_path_new, 'rb').read()) #打開附件
        annex.add_header('Content-Disposition', 'attachment', filename=file_name_new)   
        message.attach(annex)

        #image_path = 'C:/Users/yang/Desktop/1.png'
        #image = MIMEImage(open(image_path , 'rb').read(), imageFile.split('.')[-1])
        #image.add_header('Content-Disposition', 'attachment', filename=image_path.split('/')[-1])
        #message.attach(image)
        
        #登入郵箱發送報表
        server = smtplib.SMTP(smtp_ip)#端口默認是25,所以不用指定
        server.login(sender,password)
        server.sendmail(sender, receiver, message.as_string())
        server.quit()
        print('success!',datetime.datetime.now())
        
    except smtplib.SMTPException as e:
        print('error:',e,datetime.datetime.now()) #打印錯誤
            
if __name__ == '__main__':
#參數設置
    #數據庫參數設置
    host='localhost'#數據庫ip地址
    port=3306#端口
    user='root'#賬戶
    passwd='XXX'#密碼
    db='XXX'#數據庫名稱
    sql="SELECT cid,max(score) as max_score FROM sc group by cid;"#報表查詢語句
    
    #發送郵件參數設置   
    sender = '[email protected]'#發送者郵箱
    password = 'XXX'#發送者郵箱授權碼
    smtp_ip='smtp.126.com'#smtp服務器ip,根據發送者郵箱而定
    receiver = ['[email protected]','[email protected]']#接收者郵箱 
    Cc_receiver=['[email protected]','[email protected]']#抄送者郵箱
    title='訂單日報'#郵件主題
    content = 'hello,這是今天的訂單日報!'#郵件內容
    file_name='訂單日報.xlsx'#報表名稱
    annex_path='C:/Users/yang/Desktop/'#報表存儲路徑,也是附件路徑
    ts='10:13'#發送郵件的定時設置,每天ts時刻運行
    
#自動創建報表併發送郵件
    print('郵件定時發送任務啓動中.......')
    schedule.every().day.at(ts).do(send_email, file_name,annex_path) # 每天某時刻運行   
    while True:
        schedule.run_pending() # 運行所有可運行的任務
        time.sleep(43200)#因爲每次發送郵件的間隔時間是一天左右,所以休眠時間可以設長些

結果 

 

授權碼的獲取

其中郵箱的授權碼不是郵箱的密碼,而是郵箱授權給第三方軟件登陸郵箱的授權。以QQ郵箱爲例,獲取授權碼步驟如下:

(1)登陸郵箱,點開設置:

(2)選擇賬戶,找到開啓SMTP,點擊開啓:

 

(3)點擊開啓後,需要本人身份驗證:

(4)驗證成功後,會出現授權碼:

這個授權碼,就是要在連接郵件的時候填上。

 附:常用SMTP和POP服務器地址

   1、QQ郵箱(mail.qq.com)
    POP3服務器地址:pop.qq.com(端口:110)
    SMTP服務器地址:smtp.qq.com(端口:25)
    
    2、搜狐郵箱(sohu.com):
    POP3服務器地址:pop3.sohu.com(端口:110)
    SMTP服務器地址:smtp.sohu.com(端口:25)
    
    3、HotMail郵箱(hotmail.com):
    POP3服務器地址:pop.live.com(端口:995)
    SMTP服務器地址:smtp.live.com(端口:587)
    
    4、移動139郵箱:
    POP3服務器地址:POP.139.com(端口:110)
    SMTP服務器地址:SMTP.139.com(端口:25)
    
    5、景安網絡郵箱:
    POP3服務器地址:POP.zzidc.com(端口:110)
    SMTP服務器地址:SMTP.zzidc.com(端口:25)
    
    6、新浪郵箱
    smtp.sina.com(端口:25)
    
    7、新浪VIP
    SMTP服務器地址:smtp.vip.sina.com(端口:25)
    
    8、126郵箱
    SMTP服務器地址:smtp.126.com(端口:25)
    
    9、139郵箱
    SMTP服務器地址:smtp.139.com(端口:25)
    
    10、163網易郵箱
    SMTP服務器地址:smtp.163.com(端口:25) 
 

如果對你有幫助,請點下贊,予人玫瑰手有餘香!

時時仰望天空,理想就會離現實越來越近!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章