#!/usr/bin/env python
# Send mail to MBARI SMTP server.
# Adapted from example at 
# http://code4reference.com/2013/07/simple-python-script-to-send-an-email/
from smtplib import SMTP
from smtplib import SMTPException
from email.mime.text import MIMEText
import sys
 
#Global varialbes
SMTP_SERVER = "mbari.org.inbound10.mxlogic.net"
SMTP_PORT = 25
TEXT_SUBTYPE = "plain"
 
def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)
 
def send_email(sender, subject, content, recipientList):
    """This method sends an email"""    
     
    #Create the message
    msg = MIMEText(content, TEXT_SUBTYPE)
    msg["Subject"] = subject
    msg["From"] = sender
    msg["To"] = listToStr(recipientList)
     
    try:
      print 'Using ' + SMTP_SERVER + ', port ' + str(SMTP_PORT)
      smtpObj = SMTP(SMTP_SERVER, SMTP_PORT)
      #Identify yourself to SMTP server.
      smtpObj.ehlo()
      #Send email
      smtpObj.sendmail(sender, recipientList, msg.as_string())
      #close connection and session.
      smtpObj.quit();
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)
 
def main(user, subject, body, recipients):
    """This is a simple main() function which demonstrates sending of email using smtplib."""
    recipientList = recipients.split()
    ### body += ": using " + SMTP_SERVER + ", port " + str(SMTP_PORT)
    send_email(user, subject, body, recipientList);
 
if __name__ == "__main__":
    """If this script is executed as stand alone then call main() function."""
    if len(sys.argv) == 5:
        main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
    else:
        print "usage: sender subject body recipient(s)"
        print "(enclose multiple recipients in quotes, separated by space)"
        sys.exit(0)
