#! /usr/bin/python
# -*- coding: utf-8 -*-
# author: Andre J. Aberer
# license: GPLv3
# 
# This is a wrapper script, that reads addresses from a csv file and
# writes mail to them

import sendMail # be sure that sendMail.py is on your PYTHON_PATH
import csv
import time 

# mail variables
fileName = "database.csv"
myAddress = "Andre Aberer <mail.address@provider.de>"
attachmentName = "invitation.pdf"
serverName = "server.name.de"
user = "aberer"
password = "secretPassword"    
subject = "school reunion 2009"
pdfDir =  "/home/aberer/scratch/klassentreffen/pdfs/" # a dir with all the customised pdfs

# open the csv file and sniff the dialect 
csvFile = open(fileName, "r")
dialect = csv.Sniffer().sniff(csvFile.read(1024))
csvFile.seek(0)
tab = csv.reader(csvFile, dialect)

# prepare the server for the massive amount of mails =)
smtp = sendMail.serverLogin(serverName, user,  password )

# uh, it does not recognise the header...
row = tab.next()

# iterate over the rows in the csv file and write mails
for row in tab: 
    if row[8] ==  "no" or row[4] == "": # 8: do they come?  4: do I have their email address?
        print "no mail for %s" % row[0] # fetching the column by number is a bit ugly ... =( 
        continue

    invertedName = row[0].split(" ")
    invertedName = "%s %s" % (invertedName[-1],  invertedName[0])
    toAddress = "%s <%s>" % (invertedName, row[4])
    attachment = "%s%s.pdf" % (pdfDir, "".join(row[0].split(" ")))
    body = """
Hi guys,

bla bla bla

--
Best regards,
Andre et al.\n\n
"""
    
    msg = sendMail.buildMessage(myAddress, toAddress, subject, body)
    sendMail.attachPdf(attachment, attachmentName, msg)

    try: 
        smtp.sendmail(myAddress, toAddress, msg.as_string())    
        print "OK: %s" % toAddress
    except:        
        print "FAILURE: %s" % toAddress

    # might be a good idea when so many mails are sent  
    # time.sleep(1)
        
csvFile.close()
smtp.quit()