1. 程式開發 (名稱:mail_ReadF.py)
1.1 功能說明
本程式執行後,自動寄出email,寄出的內容可依照讀取的參數檔內容而決定,參數檔可依需要,事先設定好,當程式執行後即自動帶出,參數檔可任意設定,故可靈活彈性運用,寄出各種email的內容,
參數檔設定的項目共5項,即以0 1 2 3 4 代表5種不同的要項,
如下說明
0, Subject (信主旨) 主旨後面,追加記入程式執行的日時分
1, to_address (收信者) 可填入多個 id ,若無 以from_address表示
2, attachments (附件檔) 可傳送多個附件檔
3, from_address (寄信者) 若無填入 none@hoxxx.com.tw
4, contents (信內文) 可用多行陳述信件內容
1.2 開發工具 : Python 3.8.3 [MSC v.1916 64 bit (AMD64)]。
編輯工具 Spyder 4.1.4
1.3 使用模組Module/套件 : import os , smtplib SMTP郵件傳輸協定 SMTP伺服器 smtp=smtplib.SMTP_SSL('192.168.XX.XX', 465) #SSL
其他SMTP服務:
Gmail smtp.gmail.com 64.233.189.109
Yahoo smtp.mail.yahoo.com 106.10.248.80
Hotmail smtp.live.com hkg-efz.ms-acdc.office.com 52.98.40.66 Outlook smtp-mail.outlook.com
hkg-efz.ms-acdc.office.com [40.100.54.210]
非SMTP: 直接於OUTLOOK 開啟中自動寄信
2. 實際運用:
2,1 參數檔實際說明
0,[Warning] DB export job was unsuccessful, to refer the lastest log file
1, XXXlin@xxx.com.tw, xxxlin@gmail.com
2, Dump_20230813.txt
3, ffff@xxx.com.tw
4, 課長 好
4,
4, 標題所示 export job 執行無成功,最新log file 參考如下:
4,
4, \\D$\Datapum\xxx\Export\Dump
4, 以上通知
2.2 執行後寄出內容
件名: [Warning] DB export job was unsuccessful, to refer the lastest log file-- sent 2023/08/13 14:49
寄件者: ffff@xxx.com.tw
寄給 XXXlin@xxx.com.tw, xxxlin@gmail.com
附件檔: Dump_20230813.txt
信件本文:
課長 好
標題所示 export job 執行無成功,最新log file 參考如下:
以上通知
2.3 自動執行Bat檔,本程式檔,參數檔,需存置於同一資料夾內
3. 擴充運用:
3.1 各部門各業務的定期報表,日報月報等,可利用本程式,設定自動排程,可以自動寄出給各擔當,於非上班時間仍可自動寄信,節省人力工時,減少耽誤延遲等現象發生
3.2 可搭配各項業務自動排程,對每日或定期執行的程式,一旦執行失敗時,可及時寄出警告信,擔當可及時對應,避免事件擴大發生。
例如DB backup失敗,
電話通話時間異常,
機器關機/重新開啟現象發生
…
3.3 定期eMail 寄出記錄檔,可供確認保存,當做稽查時,備查之憑證記錄,減少人員手工紀錄工時
4. 程式(mail_ReadF.py) 撰寫內容:
------------ Python coding ------------------
# -*- coding: utf-8 -*-
"""
Created on xxx
@author: xxx
"""
import smtplib
from email.mime.multipart import MIMEMultipart #email內容載體
from email.mime.text import MIMEText #用於製作文字內文
from email.mime.base import MIMEBase #用於承載附檔
from email import encoders #用於附檔編碼
from datetime import datetime
#d=str(datetime.now().strftime('%y/%m/%d %H:%M:%S'))
d=str(datetime.now().strftime('%Y/%m/%d %H:%M'))
smtp_user = 'xxx@xxx.com.tw'
smtp_password = 'xxxxxxx'
#設定寄件資訊
# Read external txt file for getting to_address and attchments --linct
# f=open (R'D:\Users\xtmn094\.spyder-py3\linct\Subj_TO_Attach.txt','r',encoding='cp950')
f=open (R'mail_par.txt','r',encoding='cp950')
to_address = [] # 當無 1 ,無to_address時,default = 空list
attachments = [] # 當無 2 ,無副檔時,default = 空list
from_address = ' '
contents = ' ' # 當無 4 , 無contents時 default = 空string
while True: # ----- 讀取參數檔 mail_par.txt
s=f.readline().replace('\n', '')
if not s: # 讀到最後EOF
break
else:
s=s.split(',')
s0=s[0]
s =s[1: ]
while (s0 == '0'): # ----- 依據 參數 s0 值,做各項處理
Subject =','.join(s) # got S1_str string (list -> string)
Subject = Subject + d
break
while (s0 == '1'):
s1_str =','.join(s)
s1_str=s1_str.strip() # s1_str 前後之空白 str.strip()
if (len(s) < 1) or ( s1_str == '' ):
print (s1_str,'### none to_address --> ERROR ###' )
to_address = []
else:
to_address = s # got to_address list
break
while (s0 == '2'):
s1_str =','.join(s)
s1_str=s1_str.strip()
if (len(s) < 1) or ( s1_str == '' ):
attachments = []
else:
attachments = s[0: ] # got attachments list , =s 亦可
break
while (s0 == '3'):
s1_str =','.join(s)
s1_str=s1_str.strip()
if (len(s) < 1) or ( s1_str == '' ):
print (s1_str,'### none from_address --> ERROR ###' )
from_address = ' '
else:
from_address = s[0] # got from_address string
break
while (s0 == '4'):
s1_str =','.join(s) # list -> string then got contents string
contents = contents + s1_str +'\n'
break
f.close()
print ('0',Subject)
print ('1',to_address)
print ('2',attachments)
print ('3',from_address)
contents = contents +'\n'
if to_address == []:
to_address = from_address.split() # string from_a --> list
contents = contents + '### ERROR--> none to_address ###' +'\n'
if from_address == ' ':
from_address = 'none@honda-htw.com.tw' # none from_address
contents = contents + '### ERROR--> none from_address ###' +'\n'
# ------ 判斷附加檔 是否存在?
while (attachments !=[]):
import os
e_attach=[]
for a_f in attachments:
a_f=a_f.strip() # a_f.strip() 前後之空白去除
if os.path.isfile(a_f) == True:
e_attach.append(a_f) # 新增a_f 至 e_attach list
else:
contents= contents +'### ERROR--> attachment not exist '+ a_f + '\n'
attachments = e_attach # 只取得存在的檔案
break
#開始組合信件內容--to_address , attachments 為list, 其餘為string
mail = MIMEMultipart()
mail['From'] = from_address
mail['To'] = ', '.join(to_address)
mail['Subject'] = Subject
#將信件內文加到email中
mail.attach(MIMEText(contents))
#將附加檔案們加到email中 若有2, 卻無附加檔 則attachment =[''] 便跳開
if attachments != []:
for file in attachments:
with open(file, 'rb') as fp:
add_file = MIMEBase('application', "octet-stream")
add_file.set_payload(fp.read())
encoders.encode_base64(add_file)
add_file.add_header('Content-Disposition', 'attachment', filename=file)
mail.attach(add_file)
#設定smtp伺服器並寄發信件
smtp=smtplib.SMTP_SSL('192.168.xx.xx', 465) #SSL
smtp.ehlo()
smtp.login(smtp_user, smtp_password)
# 送信動作,並判斷 郵寄是否成功?
status=smtp.sendmail(from_address, to_address, mail.as_string())
if status=={}:
print("郵件傳送成功!")
else:
print("郵件傳送失敗!",status)
smtp.quit()
------------------ end of coding -------------------
#注意smtp伺服器以及mail user設定,必須為可運作之有效系統
smtp=smtplib.SMTP_SSL('192.168.xx.xx', 465)
smtp_user = 'xxx@xxx.com.tw'
smtp_password = 'xxxxxxx'
------------------ recorded by linct ----------------