~bzr-pqm/bzr/bzr.dev

2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
16
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
17
"""A convenience class around email.Message and email.MIMEMultipart."""
18
6379.6.3 by Jelmer Vernooij
Use absolute_import.
19
from __future__ import absolute_import
20
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
21
from email import (
22
    Header,
23
    Message,
24
    MIMEMultipart,
25
    MIMEText,
26
    Utils,
27
    )
28
29
from bzrlib import __version__ as _bzrlib_version
30
from bzrlib.osutils import safe_unicode
31
from bzrlib.smtp_connection import SMTPConnection
32
33
2625.6.3 by Adeodato Simó
Changes after review by John.
34
class EmailMessage(object):
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
35
    """An email message.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
36
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
37
    The constructor needs an origin address, a destination address or addresses
38
    and a subject, and accepts a body as well. Add additional parts to the
39
    message with add_inline_attachment(). Retrieve the entire formatted message
40
    with as_string().
41
42
    Headers can be accessed with get() and msg[], and modified with msg[] =.
43
    """
44
45
    def __init__(self, from_address, to_address, subject, body=None):
46
        """Create an email message.
47
48
        :param from_address: The origin address, to be put on the From header.
49
        :param to_address: The destination address of the message, to be put in
50
            the To header. Can also be a list of addresses.
51
        :param subject: The subject of the message.
52
        :param body: If given, the body of the message.
53
54
        All four parameters can be unicode strings or byte strings, but for the
55
        addresses and subject byte strings must be encoded in UTF-8. For the
56
        body any byte string will be accepted; if it's not ASCII or UTF-8,
57
        it'll be sent with charset=8-bit.
58
        """
59
        self._headers = {}
60
        self._body = body
61
        self._parts = []
62
63
        if isinstance(to_address, basestring):
64
            to_address = [ to_address ]
65
66
        to_addresses = []
67
68
        for addr in to_address:
69
            to_addresses.append(self.address_to_encoded_header(addr))
70
71
        self._headers['To'] = ', '.join(to_addresses)
72
        self._headers['From'] = self.address_to_encoded_header(from_address)
73
        self._headers['Subject'] = Header.Header(safe_unicode(subject))
74
        self._headers['User-Agent'] = 'Bazaar (%s)' % _bzrlib_version
75
76
    def add_inline_attachment(self, body, filename=None, mime_subtype='plain'):
77
        """Add an inline attachment to the message.
78
79
        :param body: A text to attach. Can be an unicode string or a byte
80
            string, and it'll be sent as ascii, utf-8, or 8-bit, in that
81
            preferred order.
82
        :param filename: The name for the attachment. This will give a default
83
            name for email programs to save the attachment.
84
        :param mime_subtype: MIME subtype of the attachment (eg. 'plain' for
85
            text/plain [default]).
86
87
        The attachment body will be displayed inline, so do not use this
88
        function to attach binary attachments.
89
        """
90
        # add_inline_attachment() has been called, so the message will be a
91
        # MIMEMultipart; add the provided body, if any, as the first attachment
92
        if self._body is not None:
93
            self._parts.append((self._body, None, 'plain'))
94
            self._body = None
95
96
        self._parts.append((body, filename, mime_subtype))
97
98
    def as_string(self, boundary=None):
99
        """Return the entire formatted message as a string.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
100
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
101
        :param boundary: The boundary to use between MIME parts, if applicable.
102
            Used for tests.
103
        """
104
        if not self._parts:
2639.1.2 by John Arbash Meinel
Some cleanups for the EmailMessage class.
105
            msgobj = Message.Message()
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
106
            if self._body is not None:
2625.6.3 by Adeodato Simó
Changes after review by John.
107
                body, encoding = self.string_with_encoding(self._body)
2639.1.2 by John Arbash Meinel
Some cleanups for the EmailMessage class.
108
                msgobj.set_payload(body, encoding)
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
109
        else:
2639.1.2 by John Arbash Meinel
Some cleanups for the EmailMessage class.
110
            msgobj = MIMEMultipart.MIMEMultipart()
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
111
112
            if boundary is not None:
2639.1.2 by John Arbash Meinel
Some cleanups for the EmailMessage class.
113
                msgobj.set_boundary(boundary)
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
114
115
            for body, filename, mime_subtype in self._parts:
2625.6.3 by Adeodato Simó
Changes after review by John.
116
                body, encoding = self.string_with_encoding(body)
117
                payload = MIMEText.MIMEText(body, mime_subtype, encoding)
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
118
119
                if filename is not None:
120
                    content_type = payload['Content-Type']
121
                    content_type += '; name="%s"' % filename
122
                    payload.replace_header('Content-Type', content_type)
123
124
                payload['Content-Disposition'] = 'inline'
2639.1.2 by John Arbash Meinel
Some cleanups for the EmailMessage class.
125
                msgobj.attach(payload)
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
126
127
        # sort headers here to ease testing
128
        for header, value in sorted(self._headers.items()):
2639.1.2 by John Arbash Meinel
Some cleanups for the EmailMessage class.
129
            msgobj[header] = value
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
130
2639.1.2 by John Arbash Meinel
Some cleanups for the EmailMessage class.
131
        return msgobj.as_string()
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
132
133
    __str__ = as_string
134
135
    def get(self, header, failobj=None):
136
        """Get a header from the message, returning failobj if not present."""
137
        return self._headers.get(header, failobj)
138
139
    def __getitem__(self, header):
140
        """Get a header from the message, returning None if not present.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
141
2625.6.3 by Adeodato Simó
Changes after review by John.
142
        This method intentionally does not raise KeyError to mimic the behavior
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
143
        of __getitem__ in email.Message.
144
        """
145
        return self._headers.get(header, None)
146
147
    def __setitem__(self, header, value):
148
        return self._headers.__setitem__(header, value)
149
150
    @staticmethod
151
    def send(config, from_address, to_address, subject, body, attachment=None,
6592.1.1 by Vincent Ladeuil
Fix minor incompatible change in email python 2.7.6 module.
152
             attachment_filename=None, attachment_mime_subtype='plain'):
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
153
        """Create an email message and send it with SMTPConnection.
154
155
        :param config: config object to pass to SMTPConnection constructor.
156
157
        See EmailMessage.__init__() and EmailMessage.add_inline_attachment()
158
        for an explanation of the rest of parameters.
159
        """
160
        msg = EmailMessage(from_address, to_address, subject, body)
161
        if attachment is not None:
162
            msg.add_inline_attachment(attachment, attachment_filename,
163
                    attachment_mime_subtype)
164
        SMTPConnection(config).send_email(msg)
165
166
    @staticmethod
167
    def address_to_encoded_header(address):
168
        """RFC2047-encode an address if necessary.
169
170
        :param address: An unicode string, or UTF-8 byte string.
171
        :return: A possibly RFC2047-encoded string.
172
        """
173
        # Can't call Header over all the address, because that encodes both the
174
        # name and the email address, which is not permitted by RFCs.
175
        user, email = Utils.parseaddr(address)
176
        if not user:
177
            return email
178
        else:
179
            return Utils.formataddr((str(Header.Header(safe_unicode(user))),
180
                email))
181
182
    @staticmethod
2625.6.3 by Adeodato Simó
Changes after review by John.
183
    def string_with_encoding(string_):
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
184
        """Return a str object together with an encoding.
185
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
186
        :param string\\_: A str or unicode object.
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
187
        :return: A tuple (str, encoding), where encoding is one of 'ascii',
188
            'utf-8', or '8-bit', in that preferred order.
189
        """
190
        # Python's email module base64-encodes the body whenever the charset is
191
        # not explicitly set to ascii. Because of this, and because we want to
192
        # avoid base64 when it's not necessary in order to be most compatible
193
        # with the capabilities of the receiving side, we check with encode()
194
        # and decode() whether the body is actually ascii-only.
2625.6.3 by Adeodato Simó
Changes after review by John.
195
        if isinstance(string_, unicode):
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
196
            try:
2625.6.3 by Adeodato Simó
Changes after review by John.
197
                return (string_.encode('ascii'), 'ascii')
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
198
            except UnicodeEncodeError:
2625.6.3 by Adeodato Simó
Changes after review by John.
199
                return (string_.encode('utf-8'), 'utf-8')
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
200
        else:
201
            try:
2625.6.3 by Adeodato Simó
Changes after review by John.
202
                string_.decode('ascii')
203
                return (string_, 'ascii')
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
204
            except UnicodeDecodeError:
205
                try:
2625.6.3 by Adeodato Simó
Changes after review by John.
206
                    string_.decode('utf-8')
207
                    return (string_, 'utf-8')
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
208
                except UnicodeDecodeError:
2625.6.3 by Adeodato Simó
Changes after review by John.
209
                    return (string_, '8-bit')