
#!/bin/env python
# Copyright 2007 Jon Dubovsky (jon@dubovsky.com)
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""Command-line program to send email via an SMTP server."""

strLicense = """Copyright 2007 Jon Dubovsky (jon@dubovsky.com)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>."""
strVersion = "%%prog 0.01  %s" % strLicense


from optparse import OptionParser
import smtplib, sys

def main():
   strUsage = """%prog [options] <smtp server> <from email addr> <to email addr> <subject>

Reads the body of the email from stdin unless --body or --body-file are
given and sends the resulting email via SMTP to the given server.

This program comes with ABSOLUTELY NO WARRANTY.  This is free software, and
you are welcome to redistribute it under certain conditions; run with
--version for details."""
   parser = OptionParser(usage=strUsage, version=strVersion)
   parser.add_option('-v', '--verbose', dest="verbosity", action="count", help='output information about our running')
   #parser.add_option('-a', '--attach', dest='file', action='append', help='attach the given file to the message (may be used multiple times)')
   parser.add_option('-u', '--smtp-user', dest='smtpuser', help='username for SMTP server (if it requires login)')
   parser.add_option('-p', '--smtp-pass', dest='smtppass', help='password for SMTP server (if it requires login)')
   parser.add_option('-t', '--to', help='additional \'To\' addresses (may be used multiple times)')
   parser.add_option('-b', '--body', dest='bodytext', help='provide the body of the message (rather than reading it from stdin)')
   parser.add_option('-f', '--body-file', dest='bodyfile', help='use a file\'s content for the body of message (rather than reading it from stdin)')
   
   (options, args) = parser.parse_args()
   
   # must have all the positional args
   if len(args) != 4:
      parser.error("missing required arguments")
   
   smtpserver = args[0]
   sender = args[1]
   recip = [ args[2] ]
   if options.to:
      recip.extend(options.to)
   
   message = ""
   for addr in recip:
      message += "To: %s\n" % addr
   message += "From: %s\n" % sender
   message += "Subject: %s\n" % args[3]
   message += "\n"            # end of email header
   if options.bodytext:
      message += options.bodytext
   elif options.bodyfile:
      message += open(options.bodyfile, 'r').read()
   else:
      # read body from stdin
      try:
         while 1:
            # warning: this will always append a newline to the last message line (at EOF)
            message += raw_input() + "\n"
      except EOFError:
         pass

   if options.verbosity:
      print "server: %s" % smtpserver
      print "sender: %s" % sender
      print "recipients: %s" % repr(recip)
      print "message follows:\n%s" % message

   session = smtplib.SMTP(smtpserver)
   # log in, if required
   if options.smtpuser or options.smtppass:
      if options.verbosity:
         print "logging in to the SMTP server as %s" % options.smtpuser
      session.login(options.smtpuser, options.smtppass)
   # send the message
   smtpresult = session.sendmail(sender, recip, message)

   if smtpresult:
      for recip in smtpresult.keys():
         print "* error: could not delivery mail to: %s (%s: %s)" % (recip, smtpresult[recip][0], smtpresult[recip][1])
      return 1
   
   return 0

if __name__ == '__main__':
   sys.exit( main() )
