#! /usr/bin/env ruby

# A program that takes as input two files, a mail template, and a csv file with a list of people to
# send a mail to.  The csv file is formatted:
#
#    companyname,jobtitle,firstname,lastname,phonenumber,emailaddress
#
# and the mail template can use markers such as <%= firstname %> which will get edited with information from
# the current person being mailshotted.  Basically this is a standard mail merge type thing but it actually
# send email rather than creates postal letters.
#
# Author:: Russel Winder
# Version:: 0.1.1
# Date:: 2007-02-08
# Copyright:: Copyright © 2004-7 Russel Winder.  All rights reserved.

require 'net/smtp'
require 'rmail'
require 'erb'

def transform( toData )
  companyname, jobtitle, firstname, lastname, phonenumber, emailaddress = toData.split( ',' )
  message = ERB.new( EmailTemplate )
  [ emailaddress , message.result( binding ) ]
end

def process( toData )
  toAddress , emailBody = transform( toData )
  mail = RMail::Message.new
  mail.body = emailBody
  mail.header.to = toAddress
  mail.header.from = 'russel@russel.org.uk'
  mail.header.subject = EmailSubjectLine
  Net::SMTP.start( 'mail.russel.org.uk' ) { | smtp | smtp.send_message( mail.to_s , FromAddress , toAddress ) }
end

FromAddress = 'russel@russel.org.uk'
if ARGV.length != 3
  puts( 'Usage: mailshot.py <mail-subject-line> <mail-template> <targets-csv-file>' )
  exit( 1 )
end
EmailSubjectLine = ARGV[0]
EmailTemplate = File.open( ARGV[1] ) { | file | file.read( ) }
File.open( ARGV[2] ) { | file | file.each { | line | process( line ) } }

