1
# Copyright (C) 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""A convenience class around smtplib."""
19
from __future__ import absolute_import
22
from email.utils import getaddresses, parseaddr
23
except ImportError: # python < 3
24
from email.Utils import getaddresses, parseaddr
40
smtp_password = config.Option('smtp_password', default=None,
42
Password to use for authentication to SMTP server.
44
smtp_server = config.Option('smtp_server', default=None,
46
Hostname of the SMTP server to use for sending email.
48
smtp_username = config.Option('smtp_username', default=None,
50
Username to use for authentication to SMTP server.
54
class SMTPError(BzrError):
56
_fmt = "SMTP error: %(error)s"
58
def __init__(self, error):
62
class SMTPConnectionRefused(SMTPError):
64
_fmt = "SMTP connection to %(host)s refused"
66
def __init__(self, error, host):
71
class DefaultSMTPConnectionRefused(SMTPConnectionRefused):
73
_fmt = "Please specify smtp_server. No server at default %(host)s."
76
class NoDestinationAddress(InternalBzrError):
78
_fmt = "Message does not have a destination address."
81
class SMTPConnection(object):
82
"""Connect to an SMTP server and send an email.
84
This is a gateway between breezy.config.Config and smtplib.SMTP. It
85
understands the basic bzr SMTP configuration information: smtp_server,
86
smtp_username, and smtp_password.
89
_default_smtp_server = 'localhost'
91
def __init__(self, config, _smtp_factory=None):
92
self._smtp_factory = _smtp_factory
93
if self._smtp_factory is None:
94
self._smtp_factory = smtplib.SMTP
96
self._config_smtp_server = config.get('smtp_server')
97
self._smtp_server = self._config_smtp_server
98
if self._smtp_server is None:
99
self._smtp_server = self._default_smtp_server
101
self._smtp_username = config.get('smtp_username')
102
self._smtp_password = config.get('smtp_password')
104
self._connection = None
107
"""If we haven't connected, connect and authenticate."""
108
if self._connection is not None:
111
self._create_connection()
112
# FIXME: _authenticate() should only be called when the server has
113
# refused unauthenticated access, so it can safely try to authenticate
114
# with the default username. JRV20090407
117
def _create_connection(self):
118
"""Create an SMTP connection."""
119
self._connection = self._smtp_factory()
121
self._connection.connect(self._smtp_server)
122
except socket.error as e:
123
if e.args[0] == errno.ECONNREFUSED:
124
if self._config_smtp_server is None:
125
raise DefaultSMTPConnectionRefused(socket.error,
128
raise SMTPConnectionRefused(socket.error,
133
# Say EHLO (falling back to HELO) to query the server's features.
134
code, resp = self._connection.ehlo()
135
if not (200 <= code <= 299):
136
code, resp = self._connection.helo()
137
if not (200 <= code <= 299):
138
raise SMTPError("server refused HELO: %d %s" % (code, resp))
140
# Use TLS if the server advertised it:
141
if self._connection.has_extn("starttls"):
142
code, resp = self._connection.starttls()
143
if not (200 <= code <= 299):
144
raise SMTPError("server refused STARTTLS: %d %s" %
146
# Say EHLO again, to check for newly revealed features
147
code, resp = self._connection.ehlo()
148
if not (200 <= code <= 299):
149
raise SMTPError("server refused EHLO: %d %s" % (code, resp))
151
def _authenticate(self):
152
"""If necessary authenticate yourself to the server."""
153
auth = config.AuthenticationConfig()
154
if self._smtp_username is None:
155
# FIXME: Since _authenticate gets called even when no authentication
156
# is necessary, it's not possible to use the default username
158
self._smtp_username = auth.get_user('smtp', self._smtp_server)
159
if self._smtp_username is None:
162
if self._smtp_password is None:
163
self._smtp_password = auth.get_password(
164
'smtp', self._smtp_server, self._smtp_username)
166
# smtplib requires that the username and password be byte
167
# strings. The CRAM-MD5 spec doesn't give any guidance on
168
# encodings, but the SASL PLAIN spec says UTF-8, so that's
170
username = osutils.safe_utf8(self._smtp_username)
171
password = osutils.safe_utf8(self._smtp_password)
173
self._connection.login(username, password)
176
def get_message_addresses(message):
177
"""Get the origin and destination addresses of a message.
179
:param message: A message object supporting get() to access its
180
headers, like email.message.Message or
181
breezy.email_message.EmailMessage.
182
:return: A pair (from_email, to_emails), where from_email is the email
183
address in the From header, and to_emails a list of all the
184
addresses in the To, Cc, and Bcc headers.
186
from_email = parseaddr(message.get('From', None))[1]
187
to_full_addresses = []
188
for header in ['To', 'Cc', 'Bcc']:
189
value = message.get(header, None)
191
to_full_addresses.append(value)
192
to_emails = [pair[1] for pair in
193
getaddresses(to_full_addresses)]
195
return from_email, to_emails
197
def send_email(self, message):
198
"""Send an email message.
200
The message will be sent to all addresses in the To, Cc and Bcc
203
:param message: An email.message.Message or
204
email.mime.multipart.MIMEMultipart object.
207
from_email, to_emails = self.get_message_addresses(message)
210
raise NoDestinationAddress
214
self._connection.sendmail(from_email, to_emails,
216
except smtplib.SMTPRecipientsRefused as e:
217
raise SMTPError('server refused recipient: %d %s' %
218
next(iter(e.recipients.values())))
219
except smtplib.SMTPResponseException as e:
220
raise SMTPError('%d %s' % (e.smtp_code, e.smtp_error))
221
except smtplib.SMTPException as e:
222
raise SMTPError(str(e))