/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: 2020-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 support.

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.utils import getaddresses, parseaddr
 
22
 
 
23
import errno
 
24
import smtplib
 
25
import socket
 
26
 
 
27
from . import (
 
28
    config,
 
29
    osutils,
 
30
    )
 
31
from .errors import (
 
32
    BzrError,
 
33
    InternalBzrError,
 
34
    )
 
35
 
 
36
 
 
37
smtp_password = config.Option('smtp_password', default=None,
 
38
                              help='''\
 
39
Password to use for authentication to SMTP server.
 
40
''')
 
41
smtp_server = config.Option('smtp_server', default=None,
 
42
                            help='''\
 
43
Hostname of the SMTP server to use for sending email.
 
44
''')
 
45
smtp_username = config.Option('smtp_username', default=None,
 
46
                              help='''\
 
47
Username to use for authentication to SMTP server.
 
48
''')
 
49
 
 
50
 
 
51
class SMTPError(BzrError):
 
52
 
 
53
    _fmt = "SMTP error: %(error)s"
 
54
 
 
55
    def __init__(self, error):
 
56
        self.error = error
 
57
 
 
58
 
 
59
class SMTPConnectionRefused(SMTPError):
 
60
 
 
61
    _fmt = "SMTP connection to %(host)s refused"
 
62
 
 
63
    def __init__(self, error, host):
 
64
        self.error = error
 
65
        self.host = host
 
66
 
 
67
 
 
68
class DefaultSMTPConnectionRefused(SMTPConnectionRefused):
 
69
 
 
70
    _fmt = "Please specify smtp_server.  No server at default %(host)s."
 
71
 
 
72
 
 
73
class NoDestinationAddress(InternalBzrError):
 
74
 
 
75
    _fmt = "Message does not have a destination address."
 
76
 
 
77
 
 
78
class SMTPConnection(object):
 
79
    """Connect to an SMTP server and send an email.
 
80
 
 
81
    This is a gateway between breezy.config.Config and smtplib.SMTP. It
 
82
    understands the basic bzr SMTP configuration information: smtp_server,
 
83
    smtp_username, and smtp_password.
 
84
    """
 
85
 
 
86
    _default_smtp_server = 'localhost'
 
87
 
 
88
    def __init__(self, config, _smtp_factory=None):
 
89
        self._smtp_factory = _smtp_factory
 
90
        if self._smtp_factory is None:
 
91
            self._smtp_factory = smtplib.SMTP
 
92
        self._config = config
 
93
        self._config_smtp_server = config.get('smtp_server')
 
94
        self._smtp_server = self._config_smtp_server
 
95
        if self._smtp_server is None:
 
96
            self._smtp_server = self._default_smtp_server
 
97
 
 
98
        self._smtp_username = config.get('smtp_username')
 
99
        self._smtp_password = config.get('smtp_password')
 
100
 
 
101
        self._connection = None
 
102
 
 
103
    def _connect(self):
 
104
        """If we haven't connected, connect and authenticate."""
 
105
        if self._connection is not None:
 
106
            return
 
107
 
 
108
        self._create_connection()
 
109
        # FIXME: _authenticate() should only be called when the server has
 
110
        # refused unauthenticated access, so it can safely try to authenticate
 
111
        # with the default username. JRV20090407
 
112
        self._authenticate()
 
113
 
 
114
    def _create_connection(self):
 
115
        """Create an SMTP connection."""
 
116
        self._connection = self._smtp_factory()
 
117
        try:
 
118
            self._connection.connect(self._smtp_server)
 
119
        except socket.error as e:
 
120
            if e.args[0] == errno.ECONNREFUSED:
 
121
                if self._config_smtp_server is None:
 
122
                    raise DefaultSMTPConnectionRefused(socket.error,
 
123
                                                       self._smtp_server)
 
124
                else:
 
125
                    raise SMTPConnectionRefused(socket.error,
 
126
                                                self._smtp_server)
 
127
            else:
 
128
                raise
 
129
 
 
130
        # Say EHLO (falling back to HELO) to query the server's features.
 
131
        code, resp = self._connection.ehlo()
 
132
        if not (200 <= code <= 299):
 
133
            code, resp = self._connection.helo()
 
134
            if not (200 <= code <= 299):
 
135
                raise SMTPError("server refused HELO: %d %s" % (code, resp))
 
136
 
 
137
        # Use TLS if the server advertised it:
 
138
        if self._connection.has_extn("starttls"):
 
139
            code, resp = self._connection.starttls()
 
140
            if not (200 <= code <= 299):
 
141
                raise SMTPError("server refused STARTTLS: %d %s" %
 
142
                                (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.Message or
 
178
            breezy.email_message.EmailMessage.
 
179
        :return: A pair (from_email, to_emails), where from_email is the email
 
180
            address in the From header, and to_emails a list of all the
 
181
            addresses in the To, Cc, and Bcc headers.
 
182
        """
 
183
        from_email = parseaddr(message.get('From', None))[1]
 
184
        to_full_addresses = []
 
185
        for header in ['To', 'Cc', 'Bcc']:
 
186
            value = message.get(header, None)
 
187
            if value:
 
188
                to_full_addresses.append(value)
 
189
        to_emails = [pair[1] for pair in
 
190
                     getaddresses(to_full_addresses)]
 
191
 
 
192
        return from_email, to_emails
 
193
 
 
194
    def send_email(self, message):
 
195
        """Send an email message.
 
196
 
 
197
        The message will be sent to all addresses in the To, Cc and Bcc
 
198
        headers.
 
199
 
 
200
        :param message: An email.message.Message or
 
201
            email.mime.multipart.MIMEMultipart object.
 
202
        :return: None
 
203
        """
 
204
        from_email, to_emails = self.get_message_addresses(message)
 
205
 
 
206
        if not to_emails:
 
207
            raise NoDestinationAddress
 
208
 
 
209
        try:
 
210
            self._connect()
 
211
            self._connection.sendmail(from_email, to_emails,
 
212
                                      message.as_string())
 
213
        except smtplib.SMTPRecipientsRefused as e:
 
214
            raise SMTPError('server refused recipient: %d %s' %
 
215
                            next(iter(e.recipients.values())))
 
216
        except smtplib.SMTPResponseException as e:
 
217
            raise SMTPError('%d %s' % (e.smtp_code, e.smtp_error))
 
218
        except smtplib.SMTPException as e:
 
219
            raise SMTPError(str(e))