#!/usr/bin/python
 
# Simple interface to the Python SMTP lib to use for sending e-mail.
# This script was writen for sending mail in scripting situations where a local mailserver is not an option or allowed.
# Usage: python mailer.py "smtp.mailserver.com" "from@email.com" "to@email.com" "Subject line" "Message body"
 
# Constructions like "`getmx to@email.com`" for the mail server or "`cat somefile.txt`" for the body are allowed.
# You can append the word 'fork' as the last argument to make the script fork into the background.
 
import smtplib, sys, time, os
 
SERVER = sys.argv[1]
FROM = sys.argv[2]
TO = [sys.argv[3]] # must be a list
SUBJECT = sys.argv[4]
TEXT = sys.argv[5]
 
# Function to do the actual sending
def send_mail():
	# Prepare actual message
 
	message = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (FROM, TO[0], SUBJECT, TEXT))
 
	# We'll try 3 times before giving up.
	t = 3
	while t > 0: 
		try:
			# Send the mail
			server = smtplib.SMTP(SERVER)
			server.sendmail(FROM, TO, message)
			server.quit()
			# Quit if we are successful.
			print "Mail sent."
			break
		except:
			# Handle exceptions by waiting 30 seconds and trying again.
			print "Caught error, sleeping 30 seconds before retry."
			time.sleep(30)
			t = t - 1
			if t == 0:
				print "Too many errors, giving up."
 
 
# We can fork into a new process if desired
if len(sys.argv) > 6:
	if sys.argv[6] == "fork":
		pid = os.fork()
		if pid:
			# Parent process, time to let the parent die off and have the child run in the background.
			sys.exit()
		else:
			# We are the child process, send that mail!
			send_mail()
	else:
		# No forking desired.
		send_mail()
else:
	# No forking option described, opting not to as default action.
	send_mail()