/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 breezy/email_message.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

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