~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smtp_connection.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-08-13 12:24:44 UTC
  • mfrom: (2694.2.2 no-local-smtp)
  • Revision ID: pqm@pqm.ubuntu.com-20070813122444-5pi8f4fwxqpgxs1x
Make error handling nicer when SMTP server not working

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
"""A convenience class around smtplib."""
18
18
 
19
19
from email import Utils
 
20
import errno
20
21
import smtplib
 
22
import socket
21
23
 
22
24
from bzrlib import ui
23
 
from bzrlib.errors import NoDestinationAddress, SMTPError
 
25
from bzrlib.errors import (
 
26
    NoDestinationAddress,
 
27
    SMTPError,
 
28
    DefaultSMTPConnectionRefused,
 
29
    SMTPConnectionRefused,
 
30
    )
24
31
 
25
32
 
26
33
class SMTPConnection(object):
33
40
 
34
41
    _default_smtp_server = 'localhost'
35
42
 
36
 
    def __init__(self, config):
 
43
    def __init__(self, config, _smtp_factory=None):
 
44
        self._smtp_factory = _smtp_factory
 
45
        if self._smtp_factory is None:
 
46
            self._smtp_factory = smtplib.SMTP
37
47
        self._config = config
38
 
        self._smtp_server = config.get_user_option('smtp_server')
 
48
        self._config_smtp_server = config.get_user_option('smtp_server')
 
49
        self._smtp_server = self._config_smtp_server
39
50
        if self._smtp_server is None:
40
51
            self._smtp_server = self._default_smtp_server
41
52
 
54
65
 
55
66
    def _create_connection(self):
56
67
        """Create an SMTP connection."""
57
 
        self._connection = smtplib.SMTP()
58
 
        self._connection.connect(self._smtp_server)
 
68
        self._connection = self._smtp_factory()
 
69
        try:
 
70
            self._connection.connect(self._smtp_server)
 
71
        except socket.error, e:
 
72
            if e.args[0] == errno.ECONNREFUSED:
 
73
                if self._config_smtp_server is None:
 
74
                    raise DefaultSMTPConnectionRefused(socket.error,
 
75
                                                       self._smtp_server)
 
76
                else:
 
77
                    raise SMTPConnectionRefused(socket.error,
 
78
                                                self._smtp_server)
 
79
            else:
 
80
                raise
59
81
 
60
82
        # If this fails, it just returns an error, but it shouldn't raise an
61
83
        # exception unless something goes really wrong (in which case we want