1. 程式人生 > >python發郵件帶excel附件

python發郵件帶excel附件

# encoding=utf-8
from sqlalchemy import create_engine
import pymysql
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import smtplib #SMTP簡單郵件傳輸協議,Python簡單封裝成了一個庫
import traceback
from email.mime.application import MIMEApplication


sql = 'select * from syw_bulk.area_code limit 10;'
engine=create_engine('mysql+pymysql://sy_ect:[email protected]:3306/syw_bulk?charset=utf8')
try:
    df = pd.read_sql(sql, con=engine)
    print('連結mysql送成功!')
    df.to_excel(r'C:/Users/SheYuanWang/Desktop/資料.xlsx')
except Exception:
    print('連結mysql失敗!')


def create_email(email_from,email_to,email_Subject,email_text,annex_path,annex_name):
    message=MIMEMultipart()
    message.attach(MIMEText(email_text,'plain','utf-8'))
    message['From']=Header(email_from,'utf-8')
    message['To']=Header(email_to,'utf-8')
    message['Subject']=Header(email_Subject,'utf-8')
    filepath='C:/Users/SheYuanWang/Desktop/資料.xlsx'
    basename = "賬本.xlsx"
    xlsxpart = MIMEApplication(open(filepath, 'rb').read())
    xlsxpart.add_header('Content-Disposition', 'attachment', filename=('gbk', '', basename))#注意:此處basename要轉換為gbk編碼,否則中文會有亂碼。
    message.attach(xlsxpart)
    return message


def send_email(sender,password,receiver,msg):
    try:
        server=smtplib.SMTP_SSL('smtp.exmail.qq.com',465)
        server.ehlo()
        server.login(sender,password)
        server.sendmail(sender,receiver,msg.as_string())
        print('郵件傳送成功!')
        server.quit()
    except Exception:
        print(traceback.print_exc()) #Python使用traceback.print_exc()來代替print e 來輸出詳細的異常資訊,traceback.print_exc()與print traceback.format_exc()效果是一樣的,format_exc()返回字串,print_exc()則直接給打印出來,print_exc()還可以接受file引數直接寫入到一個檔案,print_exc()還可以接受file引數直接寫入到一個檔案
        print('郵件傳送失敗!')


def main():
    yesterdaystr=yesterday=datetime.date.today()-atetime.timedelta(days=1)
    my_file_name='資料.xlsx'
    file_path=r'C:/Users/SheYuanWang/Desktop/資料.xlsx'
    my_email_from='大資料風控部自動報表傳送組'
    my_email_to='常小楠'
    my_email_Subject='user'+str(yesterdaystr)
    my_email_text='Dear all,附件為所需資料,請查收,祝好!大資料風控部自動報表傳送組'
    my_annex_path=file_path
    my_annex_name=my_file_name
    my_msg=create_email(my_email_from,my_email_to,my_email_Subject,my_email_text,my_annex_path,my_annex_name)
    my_sender='[email protected]'
    my_password='Sywcyn123456'
    my_receiver=['[email protected]'] #接收人郵箱列表
    send_email(my_sender,my_password,my_receiver,my_msg)
if __name__=='__main__':
    main()