[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
MIME-Version: 1.0
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

A=E4B

In fact, the text message object doesn’t check to see that the data you’re MIME-
encoding is valid per Unicode in general—we can send invalid UTF text but the receiver
may have trouble decoding it:


>>> m = MIMEText(b'A\xe4B', _charset='utf-8')
>>> print(m)
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64

QeRC

>>> b'A\xe4B'.decode('utf8')
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-2: unexpected...

>>> import base64
>>> base64.b64decode(b'QeRC')
b'A\xe4B'
>>> base64.b64decode(b'QeRC').decode('utf')
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-2: unexpected...

So what to do if we need to attach message text to composed messages if the text’s
datatype requirement is indirectly dictated by its Unicode encoding name? The generic
Message superclass doesn’t help here directly if we specify an encoding, as it exhibits
the same encoding-specific behavior:


>>> m = Message()
>>> m.set_payload('spam', charset='us-ascii')
>>> print(m)
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit

spam
>>> m = Message()
>>> m.set_payload(b'spam', charset='us-ascii')
AttributeError: 'bytes' object has no attribute 'encode'

>>> m.set_payload('spam', charset='utf-8')
TypeError: must be bytes or buffer, not str

Although we could try to work around these issues by repeating much of the code that
email runs, the redundancy would make us hopelessly tied to its current implementa-
tion and dependent upon its future changes. The following, for example, parrots the
steps that email runs internally to create a text message object for ASCII encoding text;
unlike the MIMEText class, this approach allows all data to be read from files as binary
byte strings, even if it’s simple ASCII:


944 | Chapter 13: Client-Side Scripting

Free download pdf