#!/usr/bin/python

# send_yahoo
# Copyright (C) 2005 by Richard Harris
# truenolejano@yahoo.com 
# Released under the GNU General Public License
# (See the included COPYING file)

# 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 2 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
# with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

DEBUG = 0
NOCLIENT = 0

import os, sys, time

try:
	import mechanoid
except:
	print ("""
	send_yahoo requires mechanoid, an Open Source programmatic
	browser written in Python.  Download is under 200kb.
	See http://python.org/pypi/mechanoid
	""")
	sys.exit()

try:
	from mechanoid.sites import MailDotYahoo
except:
	print ("""
	Your mechanoid version is too old and does not have the sites
	package. Update from http://python.org/pypi/mechanoid
	""")
	sys.exit()

def __debug_client(hdrs, to, cc, bcc, subject, text):
	f = open("/home/richard/send_yahoo.txt","w")
	f.write(`hdrs`)
	f.write("\n")
	f.write(to)
	f.write("\n")
	f.write(cc)
	f.write("\n")
	f.write(bcc)
	f.write("\n")
	f.write(subject)
	f.write("\n")
	f.write(text)
	f.close()
	return

def __exit(to, subject):
	now = time.ctime()
	f = open(os.path.expandvars("$HOME/yahoo.error"),'a')
	f.write('send_yahoo: '+to+' "'+subject+'" '+now+'.\n')
	f.close()
	return


## -------------------
try:
	if (NOCLIENT):
		import time
		to = "truenolejano@yahoo.com"
		cc = "moon_in_a_dewdrop@yahoo.com"
		bcc = "dos_zapatas@yahoo.com"
		subject = "test: "+time.asctime()
		text = """This is a test

	--
	Richard Harris
	"""
	else:	
		def __hdr(hdrs, key):
			for line in hdrs:
				if line.find(key) != -1:
					return line.replace(key,"")
			return ""	

		msg = sys.stdin.read()
		msg = msg.replace("\n\t", " ")
		msg = msg.split("\n")
		hdrs = msg[:msg.index("")]
		to = __hdr(hdrs,"To: ")
		cc = __hdr(hdrs,"Cc: ")
		bcc = __hdr(hdrs,"Bcc: ")
		subject = __hdr(hdrs,"Subject: ")
		text = "\n".join(msg[msg.index("")+1:])

	if (0):								# DEBUG SWITCH
		__debug_client(hdrs, to, cc, bcc, subject, text)
		sys.exit()	

	b = mechanoid.Browser()
	y = MailDotYahoo(b, DEBUG, NOCLIENT)
	response = y.go_to()
	response = y.log_in()
	response = y.compose()
	response = y.send_mail(to, cc, bcc, subject, text)
	y.check_response(response)
		
except:
	__exit(to, subject)
	if (DEBUG or NOCLIENT): raise
