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

(yzsuai) #1

applies to the name component of email addresses, and assumes that SMTP servers will
allow these to pass. This may encroach on some SMTP server issues which we don’t
have space to address in this book. See the Web for more on SMTP headers handling.
For more on headers decoding, see also file _test-i18n-headers.py in the examples pack-
age; it decodes additional subject and address-related headers using mailtools
methods, and displays them in a tkinter Text widget—a foretaste of how these will be
displayed in PyMailGUI.


Workaround: Message text generation for binary attachment payloads is broken


Our last two email Unicode issues are outright bugs which we must work around today,
though they will almost certainly be fixed in a future Python release. The first breaks
message text generation for all but trivial messages—the email package today no longer
supports generation of full mail text for messages that contain any binary parts, such
as images or audio files. Without coding workarounds, only simple emails that consist
entirely of text parts can be composed and generated in Python 3.1’s email package;
any MIME-encoded binary part causes mail text generation to fail.


This is a bit tricky to understand without poring over email’s source code (which,
thankfully, we can in the land of open source), but to demonstrate the issue, first notice
how simple text payloads are rendered as full message text when printed as we’ve
already seen:


C:\...\PP4E\Internet\Email> python
>>> from email.message import Message # generic message object
>>> m = Message()
>>> m['From'] = '[email protected]'
>>> m.set_payload(open('text.txt').read()) # payload is str text
>>> print(m) # print uses as_string()
From: [email protected]

spam
Spam
SPAM!

As we’ve also seen, for convenience, the email package also provides subclasses of the
Message object, tailored to add message headers that provide the extra descriptive details
used by email clients to know how to process the data:


>>> from email.mime.text import MIMEText # Message subclass with headers
>>> text = open('text.txt').read()
>>> m = MIMEText(text) # payload is str text
>>> m['From'] = '[email protected]'
>>> print(m)
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
From: [email protected]

938 | Chapter 13: Client-Side Scripting

Free download pdf