/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/smtp_connection.py

  • Committer: Jelmer Vernooij
  • Date: 2017-07-23 15:59:57 UTC
  • mto: This revision was merged to the branch mainline in revision 6740.
  • Revision ID: jelmer@jelmer.uk-20170723155957-rw4kqurf44fqx4x0
Move AlreadyBuilding/NotBuilding errors.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""A convenience class around smtplib."""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
from email import Utils
 
22
import errno
 
23
import smtplib
 
24
import socket
 
25
 
 
26
from . import (
 
27
    config,
 
28
    osutils,
 
29
    )
 
30
from .errors import (
 
31
    BzrError,
 
32
    InternalBzrError,
 
33
    )
 
34
 
 
35
 
 
36
smtp_password = config.Option('smtp_password', default=None,
 
37
        help='''\
 
38
Password to use for authentication to SMTP server.
 
39
''')
 
40
smtp_server = config.Option('smtp_server', default=None,
 
41
        help='''\
 
42
Hostname of the SMTP server to use for sending email.
 
43
''')
 
44
smtp_username = config.Option('smtp_username', default=None,
 
45
        help='''\
 
46
Username to use for authentication to SMTP server.
 
47
''')
 
48
 
 
49
 
 
50
class SMTPError(BzrError):
 
51
 
 
52
    _fmt = "SMTP error: %(error)s"
 
53
 
 
54
    def __init__(self, error):
 
55
        self.error = error
 
56
 
 
57
 
 
58
class SMTPConnectionRefused(SMTPError):
 
59
 
 
60
    _fmt = "SMTP connection to %(host)s refused"
 
61
 
 
62
    def __init__(self, error, host):
 
63
        self.error = error
 
64
        self.host = host
 
65
 
 
66
 
 
67
class DefaultSMTPConnectionRefused(SMTPConnectionRefused):
 
68
 
 
69
    _fmt = "Please specify smtp_server.  No server at default %(host)s."
 
70
 
 
71
 
 
72
 
 
73
class NoDestinationAddress(InternalBzrError):
 
74
 
 
75
    _fmt = "Message does not have a destination address."
 
76
 
 
77
 
 
78
 
 
79
class SMTPConnection(object):
 
80
    """Connect to an SMTP server and send an email.
 
81
 
 
82
    This is a gateway between breezy.config.Config and smtplib.SMTP. It
 
83
    understands the basic bzr SMTP configuration information: smtp_server,
 
84
    smtp_username, and smtp_password.
 
85
    """
 
86
 
 
87
    _default_smtp_server = 'localhost'
 
88
 
 
89
    def __init__(self, config, _smtp_factory=None):
 
90
        self._smtp_factory = _smtp_factory
 
91
        if self._smtp_factory is None:
 
92
            self._smtp_factory = smtplib.SMTP
 
93
        self._config = config
 
94
        self._config_smtp_server = config.get('smtp_server')
 
95
        self._smtp_server = self._config_smtp_server
 
96
        if self._smtp_server is None:
 
97
            self._smtp_server = self._default_smtp_server
 
98
 
 
99
        self._smtp_username = config.get('smtp_username')
 
100
        self._smtp_password = config.get('smtp_password')
 
101
 
 
102
        self._connection = None
 
103
 
 
104
    def _connect(self):
 
105
        """If we haven't connected, connect and authenticate."""
 
106
        if self._connection is not None:
 
107
            return
 
108
 
 
109
        self._create_connection()
 
110
        # FIXME: _authenticate() should only be called when the server has
 
111
        # refused unauthenticated access, so it can safely try to authenticate 
 
112
        # with the default username. JRV20090407
 
113
        self._authenticate()
 
114
 
 
115
    def _create_connection(self):
 
116
        """Create an SMTP connection."""
 
117
        self._connection = self._smtp_factory()
 
118
        try:
 
119
            self._connection.connect(self._smtp_server)
 
120
        except socket.error as e:
 
121
            if e.args[0] == errno.ECONNREFUSED:
 
122
                if self._config_smtp_server is None:
 
123
                    raise DefaultSMTPConnectionRefused(socket.error,
 
124
                                                       self._smtp_server)
 
125
                else:
 
126
                    raise SMTPConnectionRefused(socket.error,
 
127
                                                self._smtp_server)
 
128
            else:
 
129
                raise
 
130
 
 
131
        # Say EHLO (falling back to HELO) to query the server's features.
 
132
        code, resp = self._connection.ehlo()
 
133
        if not (200 <= code <= 299):
 
134
            code, resp = self._connection.helo()
 
135
            if not (200 <= code <= 299):
 
136
                raise SMTPError("server refused HELO: %d %s" % (code, resp))
 
137
 
 
138
        # Use TLS if the server advertised it:
 
139
        if self._connection.has_extn("starttls"):
 
140
            code, resp = self._connection.starttls()
 
141
            if not (200 <= code <= 299):
 
142
                raise SMTPError("server refused STARTTLS: %d %s" % (code, resp))
 
143
            # Say EHLO again, to check for newly revealed features
 
144
            code, resp = self._connection.ehlo()
 
145
            if not (200 <= code <= 299):
 
146
                raise SMTPError("server refused EHLO: %d %s" % (code, resp))
 
147
 
 
148
    def _authenticate(self):
 
149
        """If necessary authenticate yourself to the server."""
 
150
        auth = config.AuthenticationConfig()
 
151
        if self._smtp_username is None:
 
152
            # FIXME: Since _authenticate gets called even when no authentication
 
153
            # is necessary, it's not possible to use the default username 
 
154
            # here yet.
 
155
            self._smtp_username = auth.get_user('smtp', self._smtp_server)
 
156
            if self._smtp_username is None:
 
157
                return
 
158
 
 
159
        if self._smtp_password is None:
 
160
            self._smtp_password = auth.get_password(
 
161
                'smtp', self._smtp_server, self._smtp_username)
 
162
 
 
163
        # smtplib requires that the username and password be byte
 
164
        # strings.  The CRAM-MD5 spec doesn't give any guidance on
 
165
        # encodings, but the SASL PLAIN spec says UTF-8, so that's
 
166
        # what we'll use.
 
167
        username = osutils.safe_utf8(self._smtp_username)
 
168
        password = osutils.safe_utf8(self._smtp_password)
 
169
 
 
170
        self._connection.login(username, password)
 
171
 
 
172
    @staticmethod
 
173
    def get_message_addresses(message):
 
174
        """Get the origin and destination addresses of a message.
 
175
 
 
176
        :param message: A message object supporting get() to access its
 
177
            headers, like email.Message or breezy.email_message.EmailMessage.
 
178
        :return: A pair (from_email, to_emails), where from_email is the email
 
179
            address in the From header, and to_emails a list of all the
 
180
            addresses in the To, Cc, and Bcc headers.
 
181
        """
 
182
        from_email = Utils.parseaddr(message.get('From', None))[1]
 
183
        to_full_addresses = []
 
184
        for header in ['To', 'Cc', 'Bcc']:
 
185
            value = message.get(header, None)
 
186
            if value:
 
187
                to_full_addresses.append(value)
 
188
        to_emails = [ pair[1] for pair in
 
189
                Utils.getaddresses(to_full_addresses) ]
 
190
 
 
191
        return from_email, to_emails
 
192
 
 
193
    def send_email(self, message):
 
194
        """Send an email message.
 
195
 
 
196
        The message will be sent to all addresses in the To, Cc and Bcc
 
197
        headers.
 
198
 
 
199
        :param message: An email.Message or email.MIMEMultipart object.
 
200
        :return: None
 
201
        """
 
202
        from_email, to_emails = self.get_message_addresses(message)
 
203
 
 
204
        if not to_emails:
 
205
            raise NoDestinationAddress
 
206
 
 
207
        try:
 
208
            self._connect()
 
209
            self._connection.sendmail(from_email, to_emails,
 
210
                                      message.as_string())
 
211
        except smtplib.SMTPRecipientsRefused as e:
 
212
            raise SMTPError('server refused recipient: %d %s' %
 
213
                    next(iter(e.recipients.values())))
 
214
        except smtplib.SMTPResponseException as e:
 
215
            raise SMTPError('%d %s' % (e.smtp_code, e.smtp_error))
 
216
        except smtplib.SMTPException as e:
 
217
            raise SMTPError(str(e))