~bzr-pqm/bzr/bzr.dev

2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""A convenience class around smtplib."""
18
2535.2.3 by Adeodato Simó
Import full email.Utils module instead of individual functions, as per
19
from email import Utils
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
20
import errno
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
21
import smtplib
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
22
import socket
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
23
24
from bzrlib import ui
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
25
from bzrlib.errors import (
26
    NoDestinationAddress,
27
    SMTPError,
28
    DefaultSMTPConnectionRefused,
29
    SMTPConnectionRefused,
30
    )
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
31
32
33
class SMTPConnection(object):
34
    """Connect to an SMTP server and send an email.
35
36
    This is a gateway between bzrlib.config.Config and smtplib.SMTP. It
37
    understands the basic bzr SMTP configuration information: smtp_server,
38
    smtp_username, and smtp_password.
39
    """
40
41
    _default_smtp_server = 'localhost'
42
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
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
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
47
        self._config = config
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
48
        self._config_smtp_server = config.get_user_option('smtp_server')
49
        self._smtp_server = self._config_smtp_server
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
50
        if self._smtp_server is None:
51
            self._smtp_server = self._default_smtp_server
52
53
        self._smtp_username = config.get_user_option('smtp_username')
54
        self._smtp_password = config.get_user_option('smtp_password')
55
56
        self._connection = None
57
58
    def _connect(self):
59
        """If we haven't connected, connect and authenticate."""
60
        if self._connection is not None:
61
            return
62
63
        self._create_connection()
64
        self._authenticate()
65
66
    def _create_connection(self):
67
        """Create an SMTP connection."""
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
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
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
81
82
        # If this fails, it just returns an error, but it shouldn't raise an
83
        # exception unless something goes really wrong (in which case we want
84
        # to fail anyway).
85
        self._connection.starttls()
86
87
    def _authenticate(self):
88
        """If necessary authenticate yourself to the server."""
89
        if self._smtp_username is None:
90
            return
91
92
        if self._smtp_password is None:
93
            self._smtp_password = ui.ui_factory.get_password(
94
                'Please enter the SMTP password: %(user)s@%(host)s',
95
                user=self._smtp_username,
96
                host=self._smtp_server)
97
98
        self._connection.login(self._smtp_username, self._smtp_password)
99
100
    @staticmethod
101
    def get_message_addresses(message):
102
        """Get the origin and destination addresses of a message.
103
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
104
        :param message: A message object supporting get() to access its
105
            headers, like email.Message or bzrlib.email_message.EmailMessage.
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
106
        :return: A pair (from_email, to_emails), where from_email is the email
107
            address in the From header, and to_emails a list of all the
108
            addresses in the To, Cc, and Bcc headers.
109
        """
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
110
        from_email = Utils.parseaddr(message.get('From', None))[1]
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
111
        to_full_addresses = []
112
        for header in ['To', 'Cc', 'Bcc']:
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
113
            value = message.get(header, None)
114
            if value:
115
                to_full_addresses.append(value)
2535.2.3 by Adeodato Simó
Import full email.Utils module instead of individual functions, as per
116
        to_emails = [ pair[1] for pair in
117
                Utils.getaddresses(to_full_addresses) ]
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
118
119
        return from_email, to_emails
120
121
    def send_email(self, message):
122
        """Send an email message.
123
2547.1.1 by Aaron Bentley
Add SMTPConnection class (Adeodato Simó)
124
        The message will be sent to all addresses in the To, Cc and Bcc
125
        headers.
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
126
127
        :param message: An email.Message or email.MIMEMultipart object.
128
        :return: None
129
        """
130
        from_email, to_emails = self.get_message_addresses(message)
131
132
        if not to_emails:
133
            raise NoDestinationAddress
134
135
        try:
136
            self._connect()
2547.1.1 by Aaron Bentley
Add SMTPConnection class (Adeodato Simó)
137
            self._connection.sendmail(from_email, to_emails,
138
                                      message.as_string())
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
139
        except smtplib.SMTPRecipientsRefused, e:
2535.2.4 by Adeodato Simó
Don't use BzrCommandError in non-UI code; create and use an SMTPError
140
            raise SMTPError('server refused recipient: %d %s' %
141
                    e.recipients.values()[0])
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
142
        except smtplib.SMTPResponseException, e:
2535.2.4 by Adeodato Simó
Don't use BzrCommandError in non-UI code; create and use an SMTPError
143
            raise SMTPError('%d %s' % (e.smtp_code, e.smtp_error))
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
144
        except smtplib.SMTPException, e:
2535.2.4 by Adeodato Simó
Don't use BzrCommandError in non-UI code; create and use an SMTPError
145
            raise SMTPError(str(e))