#!/usr/bin/env python

FROM = "Christian Reis <kiko@async.com.br>"
CC = "Renata Pontin <renata@icmc.sc.usp.br>, " + FROM
SUBJECT = "Request for help in OSS/Free Software survey" 

MESSAGE = open("MESSAGE.txt").read()

HEADER = """From: %s\r\nTo: %s\r\nCC: %s\r\nSubject: %s\r\n\r\n"""

TARGETS = "TARGETS"

SENT = open("TARGETS.GONE").read()

import smtplib
smtp = smtplib.SMTP('localhost')

target_file = open(TARGETS).readlines()
for line in target_file:
    line = line.split("#")[0].strip()
    if not line:
        continue
    project = line[0:15].strip()
    name = line[56:].strip()
#    project = line[0:28].strip()
#    name = line[70:].strip()
    if name:
        firstname = name.split()[0]
    else:
        firstname = "there"
    email = line[15:56].strip()
    if SENT.find(email) != -1:
        print "WARNING: not sending to %s because he's in SENT" % name
        continue
#    email = line[28:70].strip()
    if email[0] == "<":
        email = email[1:]
    if email[-1] == ">":
        email = email[:-1]
    if email.find("spam") != -1 and email.find("spamcop") == -1:
        print "WARNING: not sending to %s because email has spam" % name
        continue
    email = email.replace(" at ", "@")
    email = email.replace(" dash ", "-")
    email = email.replace(" dot ", ".")
    email = email.replace(" ", ".")
    if "@" not in email:
        print "WARNING: not sending to %s because email has no @" % name
        continue
    if SENT.find(email) != -1 or (name and SENT.find(name) != -1):
        print "WARNING: not sending to %s because he's in SENT" % name
        continue
    toaddr = "%s <%s>" % (name, email)
#    toaddr = "Christian Reis <kiko@async.com.br>"
    msg = MESSAGE % (firstname, project)
    header = HEADER % (FROM, toaddr,  CC, SUBJECT)
    print header + msg
#    smtp.sendmail(FROM, "<%s>" % email, header+msg)
#    smtp.sendmail(FROM, CC, header+msg)
#    smtp.sendmail(FROM, FROM, header+msg)
#    smtp.sendmail(FROM, "<jdahlin@async.com.br>", header+msg)
