| 1 | \declaremodule{standard}{email.parser}
|
|---|
| 2 | \modulesynopsis{Parse flat text email messages to produce a message
|
|---|
| 3 | object structure.}
|
|---|
| 4 |
|
|---|
| 5 | Message object structures can be created in one of two ways: they can be
|
|---|
| 6 | created from whole cloth by instantiating \class{Message} objects and
|
|---|
| 7 | stringing them together via \method{attach()} and
|
|---|
| 8 | \method{set_payload()} calls, or they can be created by parsing a flat text
|
|---|
| 9 | representation of the email message.
|
|---|
| 10 |
|
|---|
| 11 | The \module{email} package provides a standard parser that understands
|
|---|
| 12 | most email document structures, including MIME documents. You can
|
|---|
| 13 | pass the parser a string or a file object, and the parser will return
|
|---|
| 14 | to you the root \class{Message} instance of the object structure. For
|
|---|
| 15 | simple, non-MIME messages the payload of this root object will likely
|
|---|
| 16 | be a string containing the text of the message. For MIME
|
|---|
| 17 | messages, the root object will return \code{True} from its
|
|---|
| 18 | \method{is_multipart()} method, and the subparts can be accessed via
|
|---|
| 19 | the \method{get_payload()} and \method{walk()} methods.
|
|---|
| 20 |
|
|---|
| 21 | There are actually two parser interfaces available for use, the classic
|
|---|
| 22 | \class{Parser} API and the incremental \class{FeedParser} API. The classic
|
|---|
| 23 | \class{Parser} API is fine if you have the entire text of the message in
|
|---|
| 24 | memory as a string, or if the entire message lives in a file on the file
|
|---|
| 25 | system. \class{FeedParser} is more appropriate for when you're reading the
|
|---|
| 26 | message from a stream which might block waiting for more input (e.g. reading
|
|---|
| 27 | an email message from a socket). The \class{FeedParser} can consume and parse
|
|---|
| 28 | the message incrementally, and only returns the root object when you close the
|
|---|
| 29 | parser\footnote{As of email package version 3.0, introduced in
|
|---|
| 30 | Python 2.4, the classic \class{Parser} was re-implemented in terms of the
|
|---|
| 31 | \class{FeedParser}, so the semantics and results are identical between the two
|
|---|
| 32 | parsers.}.
|
|---|
| 33 |
|
|---|
| 34 | Note that the parser can be extended in limited ways, and of course
|
|---|
| 35 | you can implement your own parser completely from scratch. There is
|
|---|
| 36 | no magical connection between the \module{email} package's bundled
|
|---|
|
|---|