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

(yzsuai) #1

Basic email Package Interfaces in Action


Although we can’t provide an exhaustive reference here, let’s step through a simple
interactive session to illustrate the fundamentals of email processing. To compose the
full text of a message—to be delivered with smtplib, for instance—make a Message,
assign headers to its keys, and set its payload to the message body. Converting to a
string yields the mail text. This process is substantially simpler and less error-prone
than the manual text operations we used earlier in Example 13-19 to build mail as
strings:


>>> from email.message import Message
>>> m = Message()
>>> m['from'] = 'Jane Doe <[email protected]>'
>>> m['to'] = '[email protected]'
>>> m.set_payload('The owls are not what they seem...')
>>>
>>> s = str(m)
>>> print(s)
from: Jane Doe <[email protected]>
to: [email protected]

The owls are not what they seem...

Parsing a message’s text—like the kind you obtain with poplib—is similarly simple,
and essentially the inverse: we get back a Message object from the text, with keys for
headers and a payload for the body:


>>> s # same as in prior interaction
'from: Jane Doe <[email protected]>\nto: [email protected]\n\nThe owls are not...'

>>> from email.parser import Parser
>>> x = Parser().parsestr(s)
>>> x
<email.message.Message object at 0x015EA9F0>
>>>
>>> x['From']
'Jane Doe <[email protected]>'
>>> x.get_payload()
'The owls are not what they seem...'
>>> x.items()
[('from', 'Jane Doe <[email protected]>'), ('to', '[email protected]')]

So far this isn’t much different from the older and now-defunct rfc822 module, but as
we’ll see in a moment, things get more interesting when there is more than one part.
For simple messages like this one, the message walk generator treats it as a single-part
mail, of type plain text:


>>> for part in x.walk():
... print(x.get_content_type())
... print(x.get_payload())
...
text/plain
The owls are not what they seem...

924 | Chapter 13: Client-Side Scripting

Free download pdf