f03baeac63b36e70c367cf653287ff7c0bd8460d
[user/alex/software/my-snippets.git] / mail-merge
1 #!/usr/bin/python
2
3 import sys
4 import os
5 import csv
6 import smtplib
7 import subprocess
8
9 sender_header = 'mail-merge-sender@mit.edu'
10 smtp = None
11
12 def dictize_line(header, line,):
13     line_dict = {}
14     for key, elem in zip(header, line, ):
15         line_dict[key]=elem
16     return line_dict
17
18 def setup_sendmail_smtp():
19     global smtp
20     smtp = smtplib.SMTP()
21     smtp.connect()
22 def sendmail_smtp(addrs, text):
23     global smtp
24     smtp.sendmail(sender_header, addrs, text, )
25 smtp_funcs = (setup_sendmail_smtp, sendmail_smtp, )
26
27 def sendmail_cmd(addrs, text):
28     args = ["/usr/lib/sendmail", "--", ]
29     args.extend(addrs)
30     proc = subprocess.Popen(args, stdin=subprocess.PIPE)
31     proc.communicate(text)
32 cmd_funcs = (lambda: True, sendmail_cmd)
33
34 setup_sendmail, sendmail = smtp_funcs
35 setup_sendmail, sendmail = cmd_funcs
36
37 if __name__=='__main__':
38     print "Syntax: $script $cc_addr $template $recipients"
39     setup_sendmail()
40     cc_addr = sys.argv[1]
41     email_file = sys.argv[2]
42     email = open(email_file, 'r').read()
43     reader = csv.reader(open(sys.argv[3]))
44     header = reader.next()
45     print header
46     for line in reader:
47         dct = dictize_line(header, line, )
48         print dct
49         text = email % dct
50         sendmail([dct['email'], cc_addr, ], text, )