之前用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 = 'XX@XXXXXX.com'
to_addr = 'join12@126.com'
subjcet = sys.argv[1]
text = sys.argv[2]
Image_path = sys.argv[3]
ms = MIMEMultipart()
ms["to"] = 'join12@126.com'
ms["From"] = 'XX@XXXXXX.com'
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("XX@XXXXXX.com(用户)", "密码")
mail.sendmail(from_addr, to_addr, ms.as_string())
mail.quit()
推荐阅读:
Python 的详细介绍:请点这里
Python 的下载地址:请点这里