监控 ☞ 邮件预警

阅读量: zyh 2020-05-14 09:34:44
Categories: Tags:
# $1 收件人
# $2 主题
# $3 内容
smtpServer=  # smtp 服务器地址,例如 smtp.gmail.com:xxx
sendUserEmail='[email protected]'
sendUserPassword=  # 一般发件人邮箱密码都是专用密码,并非web密码
/usr/local/bin/sendEmail -f ${sendUserEmail} -t $1 -u "$2" -m "$3" -s ${smtpServer} -xu ${sendUserEmail} -xp ${sendUserPassword} -o message-charset=utf-8
#!/usr/bin/python
#coding:utf-8
# by zyh
# python sendmail.py '收件人邮箱地址'  '主题' '邮件内容' '抄送邮箱地址' '附件绝对路径'


import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys

reload(sys)
sys.setdefaultencoding('utf8')

mail_host = 'smtp服务器地址'  # 例如 smtp.gmail.com:587
mail_user = '发件人邮箱'      # 例如 [email protected]
mail_pass = '发件人密码'

def send_mail(*args):
    argsNum=len(args[0])
    if argsNum == 4:
        filename,to_list, subject, content=args[0]
    elif argsNum == 5:
        filename,to_list, subject, content, cc_list=args[0]
    elif argsNum == 6:
        filename,to_list, subject, content, cc_list, subfile=args[0]
    me = mail_user+"<"+mail_user+">"

    #初始化邮件对象 msg
    msg = MIMEMultipart()

    msg['From'] = me
    msg['to'] = to_list
    emailList=to_list
    # 主题
    msg['Subject'] = Header(subject, 'utf-8').encode()
    # 内容
    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    # 抄送
    if 'cc_list' in vars():
        msg['Cc'] = cc_list
        emailstring = to_list+','+cc_list
        emailList=emailstring.split(",")
    # 附件
    if 'subfile' in vars():
        att1 = MIMEText(open(("%s"%subfile),'rb').read(), 'base64', 'utf8')
        att1["Content-Type"] = 'text/plain'
        att1["Content-Disposition"] = 'attachment; filename='+subfile.split('/')[-1] # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
        msg.attach(att1)
    # 发送
    try:
        print "start sendmail"
        s = smtplib.SMTP(mail_host)
        print "connect mail server suesscc"
        s.starttls()
        s.login(mail_user,mail_pass)
        print "login mail server suesscc"
        s.sendmail(me,emailList,msg.as_string())
        s.close()
        return True
    except Exception,e:
        print "%s\t%s"%(to_list,str(e))
        return False

if __name__ == "__main__":
    if len(sys.argv) < 4:
        exit()
    send_mail(sys.argv)