6 from types import StringTypes
7 from email.MIMEText import MIMEText
8 from email.Header import Header
9 from smtplib import SMTP
11 from PLC.Debug import log
12 from PLC.Faults import *
14 def sendmail(api, To, Subject, Body, From = None, Cc = None, Bcc = None):
16 Uses sendmail (must be installed and running locally) to send a
17 message to the specified recipients. If the API is running under
18 mod_python, the apache user must be listed in e.g.,
19 /etc/mail/trusted-users.
21 To, Cc, and Bcc may be addresses or lists of addresses. Each
22 address may be either a plain text address or a tuple of (name,
27 if not isinstance(To, list):
29 if Cc is not None and not isinstance(Cc, list):
31 if Bcc is not None and not isinstance(Bcc, list):
34 From = ("%s Support" % api.config.PLC_NAME,
35 api.config.PLC_MAIL_SUPPORT_ADDRESS)
37 # Create a MIME-encoded UTF-8 message
38 msg = MIMEText(Body.encode(api.encoding), _charset = api.encoding)
40 # Unicode subject headers are automatically encoded correctly
41 msg['Subject'] = Subject
43 def encode_addresses(addresses, header_name = None):
45 Unicode address headers are automatically encoded by
46 email.Header, but not correctly. The correct way is to put the
47 textual name inside quotes and the address inside brackets:
49 To: "=?utf-8?b?encoded" <recipient@domain>
51 Each address in addrs may be a tuple of (name, address) or
52 just an address. Returns a tuple of (header, addrlist)
53 representing the encoded header text and the list of plain
60 for addr in addresses:
61 if isinstance(addr, tuple):
64 name = name.encode('ascii')
65 header.append('%s <%s>' % (name, addr))
67 h = Header(name, charset = api.encoding, header_name = header_name)
68 header.append('"%s" <%s>' % (h.encode(), addr))
73 return (", ".join(header), addrs)
75 (msg['From'], from_addrs) = encode_addresses([From], 'From')
76 (msg['To'], to_addrs) = encode_addresses(To, 'To')
79 (msg['Cc'], cc_addrs) = encode_addresses(Cc, 'Cc')
83 (unused, bcc_addrs) = encode_addresses(Bcc, 'Bcc')
86 # Needed to pass some spam filters
87 msg['Reply-To'] = msg['From']
88 msg['X-Mailer'] = "Python/" + sys.version.split(" ")[0]
90 if not api.config.PLC_MAIL_ENABLED:
91 print >> log, "From: %(From)s, To: %(To)s, Subject: %(Subject)s" % msg
96 rejected = s.sendmail(from_addrs[0], to_addrs, msg.as_string(), rcpt_options = ["NOTIFY=NEVER"])
100 raise PLCAPIError, "Error sending message to " + ", ".join(rejected.keys())