/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 bzrlib/smtp_connection.py

  • Committer: Robert Collins
  • Date: 2010-05-06 23:41:35 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506234135-yivbzczw1sejxnxc
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
expected to return an object which can be used to unlock them. This reduces
duplicate code when using cleanups. The previous 'tokens's returned by
``Branch.lock_write`` and ``Repository.lock_write`` are now attributes
on the result of the lock_write. ``repository.RepositoryWriteLockResult``
and ``branch.BranchWriteLockResult`` document this. (Robert Collins)

``log._get_info_for_log_files`` now takes an add_cleanup callable.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""A convenience class around smtplib."""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
 
try:
22
 
    from email.utils import getaddresses, parseaddr
23
 
except ImportError:  # python < 3
24
 
    from email.Utils import getaddresses, parseaddr
25
 
 
 
19
from email import Utils
26
20
import errno
27
21
import smtplib
28
22
import socket
29
23
 
30
 
from . import (
 
24
from bzrlib import (
31
25
    config,
32
26
    osutils,
33
27
    )
34
 
from .errors import (
35
 
    BzrError,
36
 
    InternalBzrError,
 
28
from bzrlib.errors import (
 
29
    NoDestinationAddress,
 
30
    SMTPError,
 
31
    DefaultSMTPConnectionRefused,
 
32
    SMTPConnectionRefused,
37
33
    )
38
34
 
39
35
 
40
 
smtp_password = config.Option('smtp_password', default=None,
41
 
                              help='''\
42
 
Password to use for authentication to SMTP server.
43
 
''')
44
 
smtp_server = config.Option('smtp_server', default=None,
45
 
                            help='''\
46
 
Hostname of the SMTP server to use for sending email.
47
 
''')
48
 
smtp_username = config.Option('smtp_username', default=None,
49
 
                              help='''\
50
 
Username to use for authentication to SMTP server.
51
 
''')
52
 
 
53
 
 
54
 
class SMTPError(BzrError):
55
 
 
56
 
    _fmt = "SMTP error: %(error)s"
57
 
 
58
 
    def __init__(self, error):
59
 
        self.error = error
60
 
 
61
 
 
62
 
class SMTPConnectionRefused(SMTPError):
63
 
 
64
 
    _fmt = "SMTP connection to %(host)s refused"
65
 
 
66
 
    def __init__(self, error, host):
67
 
        self.error = error
68
 
        self.host = host
69
 
 
70
 
 
71
 
class DefaultSMTPConnectionRefused(SMTPConnectionRefused):
72
 
 
73
 
    _fmt = "Please specify smtp_server.  No server at default %(host)s."
74
 
 
75
 
 
76
 
class NoDestinationAddress(InternalBzrError):
77
 
 
78
 
    _fmt = "Message does not have a destination address."
79
 
 
80
 
 
81
36
class SMTPConnection(object):
82
37
    """Connect to an SMTP server and send an email.
83
38
 
84
 
    This is a gateway between breezy.config.Config and smtplib.SMTP. It
 
39
    This is a gateway between bzrlib.config.Config and smtplib.SMTP. It
85
40
    understands the basic bzr SMTP configuration information: smtp_server,
86
41
    smtp_username, and smtp_password.
87
42
    """
93
48
        if self._smtp_factory is None:
94
49
            self._smtp_factory = smtplib.SMTP
95
50
        self._config = config
96
 
        self._config_smtp_server = config.get('smtp_server')
 
51
        self._config_smtp_server = config.get_user_option('smtp_server')
97
52
        self._smtp_server = self._config_smtp_server
98
53
        if self._smtp_server is None:
99
54
            self._smtp_server = self._default_smtp_server
100
55
 
101
 
        self._smtp_username = config.get('smtp_username')
102
 
        self._smtp_password = config.get('smtp_password')
 
56
        self._smtp_username = config.get_user_option('smtp_username')
 
57
        self._smtp_password = config.get_user_option('smtp_password')
103
58
 
104
59
        self._connection = None
105
60
 
110
65
 
111
66
        self._create_connection()
112
67
        # FIXME: _authenticate() should only be called when the server has
113
 
        # refused unauthenticated access, so it can safely try to authenticate
 
68
        # refused unauthenticated access, so it can safely try to authenticate 
114
69
        # with the default username. JRV20090407
115
70
        self._authenticate()
116
71
 
119
74
        self._connection = self._smtp_factory()
120
75
        try:
121
76
            self._connection.connect(self._smtp_server)
122
 
        except socket.error as e:
 
77
        except socket.error, e:
123
78
            if e.args[0] == errno.ECONNREFUSED:
124
79
                if self._config_smtp_server is None:
125
80
                    raise DefaultSMTPConnectionRefused(socket.error,
141
96
        if self._connection.has_extn("starttls"):
142
97
            code, resp = self._connection.starttls()
143
98
            if not (200 <= code <= 299):
144
 
                raise SMTPError("server refused STARTTLS: %d %s" %
145
 
                                (code, resp))
 
99
                raise SMTPError("server refused STARTTLS: %d %s" % (code, resp))
146
100
            # Say EHLO again, to check for newly revealed features
147
101
            code, resp = self._connection.ehlo()
148
102
            if not (200 <= code <= 299):
153
107
        auth = config.AuthenticationConfig()
154
108
        if self._smtp_username is None:
155
109
            # FIXME: Since _authenticate gets called even when no authentication
156
 
            # is necessary, it's not possible to use the default username
 
110
            # is necessary, it's not possible to use the default username 
157
111
            # here yet.
158
112
            self._smtp_username = auth.get_user('smtp', self._smtp_server)
159
113
            if self._smtp_username is None:
177
131
        """Get the origin and destination addresses of a message.
178
132
 
179
133
        :param message: A message object supporting get() to access its
180
 
            headers, like email.message.Message or
181
 
            breezy.email_message.EmailMessage.
 
134
            headers, like email.Message or bzrlib.email_message.EmailMessage.
182
135
        :return: A pair (from_email, to_emails), where from_email is the email
183
136
            address in the From header, and to_emails a list of all the
184
137
            addresses in the To, Cc, and Bcc headers.
185
138
        """
186
 
        from_email = parseaddr(message.get('From', None))[1]
 
139
        from_email = Utils.parseaddr(message.get('From', None))[1]
187
140
        to_full_addresses = []
188
141
        for header in ['To', 'Cc', 'Bcc']:
189
142
            value = message.get(header, None)
190
143
            if value:
191
144
                to_full_addresses.append(value)
192
 
        to_emails = [pair[1] for pair in
193
 
                     getaddresses(to_full_addresses)]
 
145
        to_emails = [ pair[1] for pair in
 
146
                Utils.getaddresses(to_full_addresses) ]
194
147
 
195
148
        return from_email, to_emails
196
149
 
200
153
        The message will be sent to all addresses in the To, Cc and Bcc
201
154
        headers.
202
155
 
203
 
        :param message: An email.message.Message or
204
 
            email.mime.multipart.MIMEMultipart object.
 
156
        :param message: An email.Message or email.MIMEMultipart object.
205
157
        :return: None
206
158
        """
207
159
        from_email, to_emails = self.get_message_addresses(message)
213
165
            self._connect()
214
166
            self._connection.sendmail(from_email, to_emails,
215
167
                                      message.as_string())
216
 
        except smtplib.SMTPRecipientsRefused as e:
 
168
        except smtplib.SMTPRecipientsRefused, e:
217
169
            raise SMTPError('server refused recipient: %d %s' %
218
 
                            next(iter(e.recipients.values())))
219
 
        except smtplib.SMTPResponseException as e:
 
170
                    e.recipients.values()[0])
 
171
        except smtplib.SMTPResponseException, e:
220
172
            raise SMTPError('%d %s' % (e.smtp_code, e.smtp_error))
221
 
        except smtplib.SMTPException as e:
 
173
        except smtplib.SMTPException, e:
222
174
            raise SMTPError(str(e))