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