/usr/share/pyshared/schooltool/email/mail.py is in python-schooltool 1:2.1.0-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | #
# SchoolTool - common information systems platform for school administration
# Copyright (c) 2009 Shuttleworth Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
"""
Email functionality
"""
import email.Charset
from email.MIMEText import MIMEText
from datetime import datetime
import pytz
import smtplib
import socket
from persistent import Persistent
from persistent.dict import PersistentDict
from zope.container.btree import BTreeContainer
from zope.container.contained import Contained
from zope.container.interfaces import INameChooser
from zope.component import adapter
from zope.interface import implements, implementer
from schooltool.app.app import InitBase, StartUpBase
from schooltool.app.interfaces import IApplicationPreferences
from schooltool.app.interfaces import ISchoolToolApplication
from schooltool.common import SchoolToolMessage as _
from schooltool.email.interfaces import IEmailContained, IEmailContainer
from schooltool.email.interfaces import IEmailUtility
email.Charset.add_charset('utf-8', email.Charset.SHORTEST, None, None)
EMAIL_KEY = 'schooltool.email'
status_messages = {
10: _('The SchoolTool mail service is disabled'),
20: _("Couldn't connect to the SMTP server (${info})"),
30: _('Error sending HELO to the SMTP server (${info})'),
40: _("Couldn't login as ($username) to SMTP server (${info})"),
50: _('The server (${info}) rejected the From address: ${from_address}'),
60: _('The server (${info}) rejected the following recipient addresses: '
'${addresses}'),
70: _('The server (${info}) replied that the message data was malformed'),
}
class Email(Persistent, Contained):
implements(IEmailContained)
def __init__(self, from_address, to_addresses, body, subject=None):
self.from_address = from_address
self.to_addresses = to_addresses
self.body = body
self.subject = subject
self.status_code = None
self.status_parameters = PersistentDict()
self.time_created = pytz.utc.localize(datetime.utcnow())
self.time_sent = None
class EmailContainer(BTreeContainer):
implements(IEmailContainer)
enabled = None
hostname = None
port = None
username = None
password = None
tls = None
class EmailAppStartup(StartUpBase):
def __call__(self):
if EMAIL_KEY not in self.app:
self.app[EMAIL_KEY] = EmailContainer()
class EmailInit(InitBase):
def __call__(self):
self.app[EMAIL_KEY] = EmailContainer()
@implementer(IEmailContainer)
@adapter(ISchoolToolApplication)
def getEmailContainer(app):
return app.get(EMAIL_KEY)
class EmailUtility(object):
implements(IEmailUtility)
smtp_factory = None
def getEmailContainer(self):
app = ISchoolToolApplication(None)
return IEmailContainer(app)
def getApplicationTimezone(self):
app = ISchoolToolApplication(None)
return pytz.timezone(IApplicationPreferences(app).timezone)
def emailAsString(self, email):
message = MIMEText(email.body.encode('utf-8'), 'plain', 'utf-8')
message['From'] = email.from_address.encode('utf-8')
message['To'] = ', '.join([address.encode('utf-8')
for address in email.to_addresses])
if email.subject is not None:
message['Subject'] = email.subject.encode('utf-8')
time_format = '%a, %d %b %Y %H:%M:%S %z'
application_timezone = self.getApplicationTimezone()
time_created = email.time_created.astimezone(application_timezone)
message['Date'] = time_created.strftime(time_format).encode('utf-8')
return message.as_string()
def queue(self, email, status_code=None, status_parameters={}):
email.status_code = status_code
email.status_parameters.update(status_parameters)
email.time_sent = pytz.utc.localize(datetime.utcnow())
if email.__parent__ is not self.container:
name = INameChooser(self.container).chooseName('', email)
self.container[name] = email
def enabled(self):
if self.smtp_factory is None:
return False
container = self.getEmailContainer()
return container.enabled
def send(self, email):
self.container = self.getEmailContainer()
if not self.enabled():
self.queue(email, 10)
return False
server_info = '%s:%d' % (self.container.hostname,
self.container.port or 25)
try:
connection = self.smtp_factory()
if self.container.port:
port = str(self.container.port)
else:
port = '25'
connection.connect(self.container.hostname, port)
code, response = connection.ehlo()
if code < 200 or code >= 300:
code, response = connection.helo()
if code < 200 or code >= 300:
raise smtplib.SMTPHeloError(code, response)
if connection.has_extn('starttls') and self.container.tls:
connection.starttls()
connection.ehlo()
if connection.does_esmtp:
if self.container.username is not None and \
self.container.password is not None:
connection.login(self.container.username,
self.container.password)
except (socket.error,), e:
self.queue(email, 20, {'info': server_info})
return False
except (smtplib.SMTPHeloError,), e:
self.queue(email, 30, {'info': server_info})
connection.quit()
return False
except (smtplib.SMTPException,), e:
self.queue(email, 40, {'info': server_info,
'username': self.container.username})
connection.quit()
return False
message = self.emailAsString(email)
result = {}
try:
result = connection.sendmail(email.from_address,
email.to_addresses,
message)
except (smtplib.SMTPSenderRefused,), e:
self.queue(email, 50, {'info': server_info,
'from_address': e.sender})
connection.quit()
return False
except (smtplib.SMTPRecipientsRefused,), e:
addresses = e.recipients.keys()
self.queue(email, 60, {'info': server_info,
'addresses': ', '.join(addresses)})
connection.quit()
return False
except (smtplib.SMTPHeloError,), e:
self.queue(email, 30, {'info': server_info})
connection.quit()
return False
except (smtplib.SMTPDataError,), e:
self.queue(email, 70, {'info': server_info})
connection.quit()
return False
if result:
addresses = [address for address in email.to_addresses
if address in result.keys()]
email.to_addresses = addresses[:]
self.queue(email, 60, {'info': server_info,
'addresses': ', '.join(addresses)})
connection.quit()
return False
connection.quit()
return True
class SMTPEmailUtility(EmailUtility):
smtp_factory = smtplib.SMTP
|