#!/usr/bin/env python3

# Summary:
#   This script simply sends an email. It uses a Trimble email relay and so
#   will work only within the Trimble network.
#
#   The basic usage is...
#       sendmesg.py -e FROM_AND_TO_EMAIL_ADDR -s SUBJECT -b BODY
#
#   There is also an option "-f FILE" parameter that may be used to attach
#   one or more files to the email message. Only PNG, JPG, or JPEG files
#   are recognized.

# Import smtplib for the actual sending function
import re, smtplib, sys

from os.path import basename

# Import the email modules we'll need
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

#
# -------------------------------------------------- sendMesg()
#
def sendMesg( smtpServer, fromAddr, toAddr, subject, body, attachments ):
  ## # Open a plain text file for reading.  For this example, assume that
  ## # the text file contains only ASCII characters.
  ## fp = open(textfile, 'rb')
  ## # Create a text/plain message
  ## msg = MIMEText(fp.read())
  ## fp.close()
  msg = None
  if len(attachments) > 0:
    #print "Make this multipart"
    msg = MIMEMultipart()
    msg.attach( MIMEText(body) )
  else:
    #print "Not Multipart"
    msg = MIMEText( body )

  # me == the sender's email address
  # you == the recipient's email address
  msg['Subject'] = subject
  msg['From'] = fromAddr
  msg['To'] = toAddr

  isImage = re.compile(".+\.(png|PNG|jpg|JPG|jpeg|JPEG)$")
  for attachment in attachments:
    with open(attachment, "rb") as fil:
      bname = basename(attachment)
      part = MIMEApplication( fil.read(), Name = bname )
      part['Content-Disposition'] = 'attachment; filename="%s"' % ( bname )
      msg.attach(part)
    #if isImage.match( attachment ):
    #  fp = open(attachment, 'rb')
    #  img = MIMEImage(fp.read())
    #  fp.close()
    #  msg.attach(img)
    #else:                  # assume text for now, future: MIMEAudio, MIMEBase
    #  fp = open(attachment, 'r')
    #  txt = MIMEText(fp.read())
    #  fp.close()
    #  msg.attach(txt)

  # Send the message via our own SMTP server, but don't include the
  # envelope header.
  #s = smtplib.SMTP('localhost')
  s = smtplib.SMTP( smtpServer )
  s.sendmail(fromAddr, [toAddr], msg.as_string())
  s.quit()

#
# -------------------------------------------------- main()
#
fromAddr    = None
toAddr      = None
smtpServer  = "west-smtp1.trimble.com"
subject     = None
body        = None
attachments = []

expectSubject    = False
expectBody       = False
expectEmail      = False
expectFilename   = False
expectSmtpServer = False
errored          = False

isSwitch = re.compile("^-.*$")

for arg in sys.argv[1:]:
  # print "arg: %s" % ( arg )

  m = isSwitch.match( arg )
  if m:
    if "-s" == arg:
      expectSubject = True

    elif "-b" == arg:
      expectBody = True

    elif "-e" == arg:
      expectEmail = True

    elif "-f" == arg:
      expectFilename = True

    elif "-r" == arg:
      expectSmtpServer = True

    else:
      errored = True

  elif expectSubject:
    subject = arg
    expectSubject = False

  elif expectBody:
    body = arg
    expectBody = False

  elif expectFilename:
    attachments.append(arg)
    expectFilename = False

  elif expectEmail:
    fromAddr = arg
    toAddr   = arg
    expectEmail = False

  elif expectSmtpServer:
    smtpServer = arg
    expectSmtpServer = False

  else:
    errored = True

if errored or None == fromAddr or None == subject or None == body:
  print("Usage: %s -e EMAIL_ADDRESS -s SUBJECT -b BODY" % (basename(__file__)))
  print("                [ -r SMTP_SERVER ] [-f FILENAME [-f FILENAME2 [...]]]")
  sys.exit(1)

sendMesg( smtpServer, fromAddr, toAddr, subject, body, attachments )
