5 from types import StringTypes
6 from email.MIMEText import MIMEText
7 from email.Header import Header
8 from smtplib import SMTP
10 from PLC.Debug import log
11 from PLC.Faults import *
13 def sendmail(api, To, Subject, Body, From = None, Cc = None, Bcc = None):
15 Uses sendmail (must be installed and running locally) to send a
16 message to the specified recipients. If the API is running under
17 mod_python, the apache user must be listed in e.g.,
18 /etc/mail/trusted-users.
20 To, Cc, and Bcc may be addresses or lists of addresses. Each
21 address may be either a plain text address or a tuple of (name,
26 if not isinstance(To, list):
28 if Cc is not None and not isinstance(Cc, list):
30 if Bcc is not None and not isinstance(Bcc, list):
33 From = ("%s Support" % api.config.PLC_NAME,
34 api.config.PLC_MAIL_SUPPORT_ADDRESS)
36 # Create a MIME-encoded UTF-8 message
37 msg = MIMEText(Body.encode(api.encoding), _charset = api.encoding)
39 # Unicode subject headers are automatically encoded correctly
40 msg['Subject'] = Subject
42 def encode_addresses(addresses, header_name = None):
44 Unicode address headers are automatically encoded by
45 email.Header, but not correctly. The correct way is to put the
46 textual name inside quotes and the address inside brackets:
48 To: "=?utf-8?b?encoded" <recipient@domain>
50 Each address in addrs may be a tuple of (name, address) or
51 just an address. Returns a tuple of (header, addrlist)
52 representing the encoded header text and the list of plain
59 for addr in addresses:
60 if isinstance(addr, tuple):
63 name = name.encode('ascii')
64 header.append('%s <%s>' % (name, addr))
66 h = Header(name, charset = api.encoding, header_name = header_name)
67 header.append('"%s" <%s>' % (h.encode(), addr))
72 return (", ".join(header), addrs)
74 (msg['From'], from_addrs) = encode_addresses([From], 'From')
75 (msg['To'], to_addrs) = encode_addresses(To, 'To')
78 (msg['Cc'], cc_addrs) = encode_addresses(Cc, 'Cc')
82 (unused, bcc_addrs) = encode_addresses(Bcc, 'Bcc')
85 # Needed to pass some spam filters
86 msg['Reply-To'] = msg['From']
87 msg['X-Mailer'] = "Python/" + sys.version.split(" ")[0]
89 if not api.config.PLC_MAIL_ENABLED:
90 print >> log, "From: %(From)s, To: %(To)s, Subject: %(Subject)s" % msg
95 rejected = s.sendmail(from_addrs[0], to_addrs, msg.as_string(), rcpt_options = ["NOTIFY=NEVER"])
99 raise PLCAPIError, "Error sending message to " + ", ".join(rejected.keys())