#!/usr/bin/python

"""

	Sends a confirmation email to a shelter user.
	Just requires a code to be passed in at the command 
	line and a file for the text.

	The file can contain any of the following keys:

	$Code, $Name, $Address, $Phone, $Email, $RelatedAreas, $Password, $Website

	The first line is assumed to be the subject.

"""

import sys
import smtplib
import string
import db

# Assumes we're sending through an SMTP transport on the local machine
SMTPHOST="localhost"
FROM="join@findmeapet.com"

# Make sure we have enough arguments
if len(sys.argv) < 3:
	print "Usage: sendemail <sheltercode> <textfile>"
	sys.exit(1)

# Read the email details into memory
ft = open(sys.argv[2], "r")
subject = ft.readline().strip()
body = ft.read()
ft.close()

# Read the shelter details from the database
d = db.runQuery("SELECT ID, NAME, EMAIL, ADDRESS, RELATEDAREAS, PHONE, PASSWORD, WEBSITE FROM SHELTER WHERE ID='" + sys.argv[1] + "'")

# Construct the subject for this email
ts = subject.replace("$Code", d[0][0])
ts = ts.replace("$Name", d[0][1])
ts = ts.replace("$Email", d[0][2])
ts = ts.replace("$Address", d[0][3])
ts = ts.replace("$RelatedAreas", d[0][4])
ts = ts.replace("$Phone", d[0][5])
ts = ts.replace("$Password", d[0][6])
ts = ts.replace("$Website", d[0][7])

# Construct the body for this email
tb = body.replace("$Code", d[0][0])
tb = tb.replace("$Name", d[0][1])
tb = tb.replace("$Email", d[0][2])
tb = tb.replace("$Address", d[0][3])
tb = tb.replace("$RelatedAreas", d[0][4])
tb = tb.replace("$Phone", d[0][5])
tb = tb.replace("$Password", d[0][6])
tb = tb.replace("$Website", d[0][7])

# Make the message
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % ( FROM, d[0][2], ts, tb )

# Send the email
print "Sending mail to: %s" % d[0][2]
smtp = smtplib.SMTP()
smtp.connect(SMTPHOST, 25)
smtp.sendmail(FROM, d[0][2], msg)

