之前用shell寫了些定期生成Cacti流量報表,但是CVS文件和png圖片,用shell腳本將文件以附件形式發送很麻煩。這裡用python寫了個腳本發送附件。還沒有與shell腳本對接,需要在這個腳本裡去調用shell腳本然後返回文件名以便發送。
#!/usr/bin/env python
import email
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
#from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
import smtplib
import os
import sys
mail_server = 'smtp.XXXXXX.com'#公司內部郵件服務器
mail_server_port = 25
from_addr = '[email protected]'
to_addr = '[email protected]'
subjcet = sys.argv[1]
text = sys.argv[2]
Image_path = sys.argv[3]
ms = MIMEMultipart()
ms["to"] = '[email protected]'
ms["From"] = '[email protected]'
ms["Subject"] = subjcet
msText = MIMEText(text)
ms.attach(msText)
fp = open(Image_path,'rb')
msImage = MIMEImage(fp.read())
fp.close()
msImage.add_header('Content-ID','<image1>')
ms.attach(msImage)
mail = smtplib.SMTP(mail_server, mail_server_port)
#mail.set_debuglevel(1) #調試
mail.starttls()
mail.login("[email protected](用戶)", "密碼")
mail.sendmail(from_addr, to_addr, ms.as_string())
mail.quit()