9ea66f7103c17d4369b561abfdee781b8bada564
[monitor.git] / mailer.py
1 #!/usr/bin/python2
2 #
3 # Copyright (c) 2004  The Trustees of Princeton University (Trustees).
4 #
5 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
6 #
7 # $Id: $
8 from emailTxt import *
9 import xml, xmlrpclib
10 import smtplib
11
12 MTA="localhost"
13 FROM="support@planet-lab.org"
14
15 XMLRPC_SERVER = 'https://www.planet-lab.org/PLCAPI/'
16
17 def siteId(hostname):
18         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
19         anon = {'AuthMethod': "anonymous"}
20         site_id = api.AnonAdmQuerySite (anon, {"node_hostname": hostname})
21         if len(site_id) == 1:  
22                 loginbase = api.AnonAdmGetSites (anon, site_id, ["login_base"])
23                 return loginbase[0]['login_base']
24         else:
25                 raise "Unknown host" 
26
27 def email (subject, text, to, cc = None):
28         """Create a mime-message that will render HTML in popular
29         MUAs, text in better ones"""
30         import MimeWriter
31         import mimetools
32         import cStringIO
33
34         out = cStringIO.StringIO() # output buffer for our message 
35         txtin = cStringIO.StringIO(text)
36
37         writer = MimeWriter.MimeWriter(out)
38         #
39         # set up some basic headers... we put subject here
40         # because smtplib.sendmail expects it to be in the
41         # message body
42         #
43         writer.addheader("Subject", subject)
44         writer.addheader("To", to)
45         if cc: writer.addheader("CC", cc)
46         writer.addheader("MIME-Version", "1.0")
47         #
48         # start the multipart section of the message
49         # multipart/alternative seems to work better
50         # on some MUAs than multipart/mixed
51         #
52         writer.startmultipartbody("alternative")
53         writer.flushheaders()
54         #
55         # the plain text section
56         #
57         subpart = writer.nextpart()
58         subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
59         pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
60         mimetools.encode(txtin, pout, 'quoted-printable')
61         txtin.close()
62         #
63         # Now that we're done, close our writer and
64         # return the message body
65         #
66         writer.lastpart()
67         msg = out.getvalue()
68         out.close()
69
70         server = smtplib.SMTP(MTA)
71         server.sendmail(FROM, (to,cc), msg)
72         server.quit()
73
74 if __name__=="__main__":
75    import smtplib
76    import emailTxt
77
78    email('DISREGARD', emailTxt.mailtxt.STANDARD % {'hostname': "ALICE.cs.princeton.edu"}, "tech-" + siteId("alice.cs.princeton.edu") + "@sites.planet-lab.org")