#!/usr/bin/python
# Send an email with an embedded attachment.


import sys, os.path, StringIO, MimeWriter, base64
from os import getenv

# Define these once; use them twice!
path = getenv('ATTACHMENT_PATH', '')
attachmentName = getenv('ATTACHMENT_NAME', path)
strSubject = getenv('SUBJECT')
strFrom = getenv('FROM')
strTo = getenv('TO', 'NOBODY')
strBody = getenv('BODY', '')

strServer = getenv('SMTP_SERVER')
strUser = getenv('SMTP_USER')
strPass = getenv('SMTP_PASS')

strUseTLS = getenv('SMTP_USE_TLS', 'NO')
strUsePass = getenv('SMTP_USE_PASS', 'NO')

if strTo == 'NOBODY': 
	sys.exit(1)

message = StringIO.StringIO()

writer = MimeWriter.MimeWriter(message)
writer.addheader('Subject', strSubject)
writer.addheader('From', strFrom)
writer.addheader('To', strTo)

writer.startmultipartbody('mixed')

# start off with a text/plain part
part = writer.nextpart()

body = part.startbody('text/plain')
body.write(strBody)
body.write('\n')

if path != '':
	# now add an image part
	part = writer.nextpart()
	part.addheader('Content-Transfer-Encoding', 'base64')

	body = part.startbody("%s; name=%s" % ('application/octet-stream', attachmentName))
	base64.encode(open(path, 'rb'), body)

# finish off
writer.lastpart()


# Send the email
import smtplib
smtp = smtplib.SMTP()
smtp.connect(strServer)
smtp.ehlo()

if strUseTLS == 'YES':
	smtp.starttls()
	smtp.ehlo()

if strUsePass == 'YES':
	smtp.login(strUser, strPass)

smtp.sendmail(strFrom, strTo, message.getvalue())
smtp.quit()

sys.exit(0)
