#!/usr/bin/python
#coding=utf-8

## common mail module
def Usage():
    print '''Usage: mail.py <subject> <content> [ addr list (sep by ,) ]
    content in text/html MIME format
    '''
    sys.exit(0)

from datetime import datetime
import smtplib
import urllib2
import sys

if len(sys.argv) < 3:
    Usage();

mailsubject = sys.argv[1]
mailcontent = sys.argv[2]
monitor_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sender = 'itl_alarm@taomee.com'
receivers = ['lc@taomee.com']
if len(sys.argv) > 3 :
    addrlist=sys.argv[3]
    receivers = addrlist.split(',')
tolist=";".join(receivers)

def getMsg(to, subject, content, tm):
    return """From: monitor <monitor@taomee.com>
To: %s
MIME-Version: 1.0
Content-type: text/html
Subject: monitor mail: %s

<h1>monitor mail</h1>
%s
<br/> <br/>
monitor time: %s """ %(to, subject, content, tm)

def sendmail(sd, rcv, msg):
    try:
        smtpObj = smtplib.SMTP('mail.taomee.com')
        smtpObj.sendmail(sd, rcv, msg)
        print "Successfully sent email"
    except smtplib.SMTPException, e:
        print "Error: unable to send email\n%s" %(str(e))

###--------------- mail logic -------------
if __name__ == '__main__':
    try:
        message = getMsg(tolist, mailsubject, mailcontent, monitor_time)
        sendmail(sender, receivers, message)
    except urllib2.URLError,e:
        print "error: %r" %e
        sendmail()
