- subclass the correct class
[plcapi.git] / PLC / sendmail.py
1 import os
2 import sys
3 from types import StringTypes
4 from subprocess import Popen, PIPE
5
6 from PLC.Debug import log
7 from PLC.Faults import *
8
9 def sendmail(api, To, Subject, Body, From = None, Cc = "", Bcc = "", DSN = "never"):
10     """
11     Uses sendmail (must be installed and running locally) to send a
12     message to the specified recipients. If the API is running under
13     mod_python, the apache user must be listed in e.g.,
14     /etc/mail/trusted-users.
15
16     If dsn is not 'never' (e.g., 'failure', 'delay', or 'success'),
17     then the current support address (PLC_MAIL_SUPPORT_ADDRESS) will
18     receive any delivery status notification messages.
19     """
20
21     # Fix up defaults
22     if From is None:
23         From = "%s Support <%s>" % \
24                (api.config.PLC_NAME, api.config.PLC_MAIL_SUPPORT_ADDRESS)
25
26     header = {'From': From,
27               'version': sys.version.split(" ")[0],
28               'Subject': Subject}
29
30     # Accept either a string or a list of strings for each of To, Cc, and Bcc
31     for line in 'To', 'Cc', 'Bcc':
32         addresses = locals()[line]
33         if isinstance(addresses, StringTypes):
34             header[line] = addresses
35         else:
36             header[line] = ", ".join(addresses)
37
38     if not api.config.PLC_MAIL_ENABLED:
39         print >> log, "From: %(From)s, To: %(To)s, Subject: %(Subject)s" % header
40         return
41
42     p = Popen(["sendmail", "-N", DSN, "-t", "-f" + api.config.PLC_MAIL_SUPPORT_ADDRESS],
43               stdin = PIPE, stdout = PIPE, stderr = PIPE)
44
45     # Write headers
46     p.stdin.write("""
47 Content-type: text/plain
48 From: %(From)s
49 Reply-To: %(From)s
50 To: %(To)s
51 Cc: %(Cc)s
52 Bcc: %(Bcc)s
53 X-Mailer: Python/%(version)s
54 Subject: %(Subject)s
55
56 """.lstrip() % header)
57
58     # Write body
59     p.stdin.write(Body)
60
61     p.stdin.close()
62     err = p.stderr.read()
63     rc = p.wait()
64
65     # Done
66     if rc != 0:
67         raise PLCAPIError, err