email.contentmanager
:管理 MIME 内容
¶
注意
The contentmanager module has been included in the standard library on a provisional basis . Backwards incompatible changes (up to and including removal of the module) may occur if deemed necessary by the core developers.
3.4 版新增: 作为 暂行模块 .
The
message
module provides a class that can represent an arbitrary email message. That basic message model has a useful and flexible API, but it provides only a lower-level API for interacting with the generic parts of a message (the headers, generic header parameters, and the payload, which may be a list of sub-parts). This module provides classes and tools that provide an enhanced and extensible API for dealing with various specific types of content, including the ability to retrieve the content of the message as a specialized object type rather than as a simple bytes object. The module automatically takes care of the RFC-specified MIME details (required headers and parameters, etc.) for the certain common content types content properties, and support for additional types can be added by an application using the extension mechanisms.
This module defines the eponymous “Content Manager” classes. The base
ContentManager
class defines an API for registering content management functions which extract data from
Message
objects or insert data and headers into
Message
objects, thus providing a way of converting between
Message
objects containing data and other representations of that data (Python data types, specialized Python objects, external files, etc). The module also defines one concrete content manager:
raw_data_manager
converts between MIME content types and
str
or
bytes
data. It also provides a convenient API for managing the MIME parameters when inserting content into
Message
s. It also handles inserting and extracting
Message
objects when dealing with the
message/rfc822
content type.
Another part of the enhanced interface is subclasses of
Message
that provide new convenience API functions, including convenience methods for calling the Content Managers derived from this module.
注意
尽管
EmailMessage
and
MIMEPart
are currently documented in this module because of the provisional nature of the code, the implementation lives in the
email.message
模块。
email.message.
EmailMessage
(
policy=default
)
¶
若
policy
有指定 (它必须是实例化的
policy
class) use the rules it specifies to udpate and serialize the representation of the message. If
policy
未设置,使用
default
策略,遵循电子邮件 RFC 规则,除了行结束 (而不是 RFC 规定的
\r\n
,它使用 Python 标准
\n
行结束)。更多信息见
policy
文档编制。
This class is a subclass of
Message
. It adds the following methods:
is_attachment
(
)
¶
返回
True
if there is a
Content-Disposition
header and its (case insensitive) value is
attachment
,
False
否则。
3.4.2 版改变:
is_attachment is now a method instead of a property, for consistency with
is_multipart()
.
get_body
(
preferencelist=('related'
,
'html'
,
'plain')
)
¶
Return the MIME part that is the best candidate to be the “body” of the message.
preferencelist
must be a sequence of strings from the set
related
,
html
,和
plain
, and indicates the order of preference for the content type of the part returned.
Start looking for candidate matches with the object on which the
get_body
方法被调用。
若
related
is not included in
preferencelist
, consider the root part (or subpart of the root part) of any related encountered as a candidate if the (sub-)part matches a preference.
When encountering a
multipart/related
, check the
start
parameter and if a part with a matching
Content-ID
is found, consider only it when looking for candidate matches. Otherwise consider only the first (default root) part of the
multipart/related
.
If a part has a
Content-Disposition
header, only consider the part a candidate match if the value of the header is
inline
.
If none of the candidates matches any of the preferences in
preferneclist
,返回
None
.
Notes: (1) For most applications the only
preferencelist
combinations that really make sense are
('plain',)
,
('html', 'plain')
, and the default,
('related', 'html', 'plain')
. (2) Because matching starts with the object on which
get_body
is called, calling
get_body
在
multipart/related
will return the object itself unless
preferencelist
has a non-default value. (3) Messages (or message parts) that do not specify a
Content-Type
or whose
Content-Type
header is invalid will be treated as if they are of type
text/plain
, which may occasionally cause
get_body
to return unexpected results.
iter_attachments
(
)
¶
Return an iterator over all of the parts of the message that are not candidate “body” parts. That is, skip the first occurrence of each of
text/plain
,
text/html
,
multipart/related
,或
multipart/alternative
(unless they are explicitly marked as attachments via
Content-Disposition: attachment
), and return all remaining parts. When applied directly to a
multipart/related
, return an iterator over the all the related parts except the root part (ie: the part pointed to by the
start
parameter, or the first part if there is no
start
parameter or the
start
parameter doesn’t match the
Content-ID
of any of the parts). When applied directly to a
multipart/alternative
or a non-
multipart
, return an empty iterator.
iter_parts
(
)
¶
Return an iterator over all of the immediate sub-parts of the message, which will be empty for a non-
multipart
。(另请参阅
walk()
)。
get_content
(
*args
,
content_manager=None
,
**kw
)
¶
调用
get_content
方法在
content_manager
,将 self 传递作为消息对象,并将任何其它自变量 (或关键字) 传递作为额外自变量。若
content_manager
未指定,使用
content_manager
指定通过当前
policy
.
set_content
(
*args
,
content_manager=None
,
**kw
)
¶
调用
set_content
方法在
content_manager
,将 self 传递作为消息对象,并将任何其它自变量 (或关键字) 传递作为额外自变量。若
content_manager
未指定,使用
content_manager
指定通过当前
policy
.
转换非
multipart
消息成
multipart/related
消息,移动任何现有
Content-
头和负载到 (新的) 第一部分的
multipart
。若
boundary
is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).
make_alternative
(
boundary=None
)
¶
转换非
multipart
或
multipart/related
成
multipart/alternative
,移动任何现有
Content-
头和负载到 (新的) 第一部分的
multipart
。若
boundary
is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).
make_mixed
(
boundary=None
)
¶
转换非
multipart
,
multipart/related
,或
multipart-alternative
成
multipart/mixed
,移动任何现有
Content-
头和负载到 (新的) 第一部分的
multipart
。若
boundary
is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).
若消息为
multipart/related
,创建新的消息对象,将所有自变量传递给其
set_content()
方法,和
attach()
它到
multipart
。若消息是非
multipart
,调用
make_related()
然后按上文继续进行。若消息是任何其它类型的
multipart
,引发
TypeError
。若
content_manager
未指定,使用
content_manager
指定通过当前
policy
。若添加部分没有
Content-Disposition
header, add one with the value
inline
.
add_alternative
(
*args
,
content_manager=None
,
**kw
)
¶
若消息为
multipart/alternative
,创建新的消息对象,将所有自变量传递给其
set_content()
方法,和
attach()
它到
multipart
。若消息是非
multipart
or
multipart/related
,调用
make_alternative()
然后按上文继续进行。若消息是任何其它类型的
multipart
,引发
TypeError
。若
content_manager
未指定,使用
content_manager
指定通过当前
policy
.
add_attachment
(
*args
,
content_manager=None
,
**kw
)
¶
若消息为
multipart/mixed
,创建新的消息对象,将所有自变量传递给其
set_content()
方法,和
attach()
它到
multipart
。若消息是非
multipart
,
multipart/related
,或
multipart/alternative
,调用
make_mixed()
and then proceed as above. If
content_manager
未指定,使用
content_manager
指定通过当前
policy
。若添加部分没有
Content-Disposition
header, add one with the value
attachment
. This method can be used both for explicit attachments (
Content-Disposition: attachment
and
inline
attachments (
Content-Disposition: inline
), by passing appropriate options to the
content_manager
.
clear
(
)
¶
移除负载和所有头。
clear_content
(
)
¶
移除负载和所有
Content-
头,完整保留所有其它头及其原始次序。
email.message.
MIMEPart
(
policy=default
)
¶
This class represents a subpart of a MIME message. It is identical to
EmailMessage
, except that no
MIME-Version
headers are added when
set_content()
is called, since sub-parts do not need their own
MIME-Version
头。
email.contentmanager.
ContentManager
¶
内容管理器的基类。提供标准注册机制注册的转换器介于 MIME 内容和其它表示,及
get_content
and
set_content
分派方法。
get_content
(
msg
,
*args
,
**kw
)
¶
查找处理程序函数基于
mimetype
of
msg
(见下一段落),透过传递所有自变量调用它,并返回调用结果。预期处理程序会提取负载从
msg
并返回有关提取数据编码信息的对象。
要找到处理程序,在注册表中查找以下键,发现首个键时停止:
maintype/subtype
)
maintype
若这些键未产生处理程序,引发
KeyError
对于完整 MIME 类型。
set_content
(
msg
,
obj
,
*args
,
**kw
)
¶
若
maintype
is
multipart
,引发
TypeError
; otherwise look up a handler function based on the type of
obj
(see next paragraph), call
clear_content()
在
msg
, and call the handler function, passing through all arguments. The expectation is that the handler will transform and store
obj
into
msg
, possibly making other changes to
msg
as well, such as adding various MIME headers to encode information needed to interpret the stored data.
To find the handler, obtain the type of
obj
(
typ = type(obj)
), and look for the following keys in the registry, stopping with the first one found:
typ
)
typ.__module__ + '.' +
typ.__qualname__
).
typ.__qualname__
)
typ.__name__
).
If none of the above match, repeat all of the checks above for each of the types in the
MRO
(
typ.__mro__
). Finally, if no other key yields a handler, check for a handler for the key
None
. If there is no handler for
None
,引发
KeyError
for the fully qualified name of the type.
Also add a
MIME-Version
header if one is not present (see also
MIMEPart
).
add_get_handler
(
key
,
handler
)
¶
Record the function
handler
as the handler for
key
. For the possible values of
key
,见
get_content()
.
add_set_handler
(
typekey
,
handler
)
¶
Record
handler
as the function to call when an object of a type matching
typekey
被传递给
set_content()
. For the possible values of
typekey
,见
set_content()
.
Currently the email package provides only one concrete content manager,
raw_data_manager
, although more may be added in the future.
raw_data_manager
是
content_manager
provided by
EmailPolicy
and its derivatives.
email.contentmanager.
raw_data_manager
¶
This content manager provides only a minimum interface beyond that provided by
Message
itself: it deals only with text, raw byte strings, and
Message
objects. Nevertheless, it provides significant advantages compared to the base API:
get_content
on a text part will return a unicode string without the application needing to manually decode it,
set_content
provides a rich set of options for controlling the headers added to a part and controlling the content transfer encoding, and it enables the use of the various
add_
methods, thereby simplifying the creation of multipart messages.
email.contentmanager.
get_content
(
msg
,
errors='replace'
)
¶
Return the payload of the part as either a string (for
text
parts), a
EmailMessage
object (for
message/rfc822
parts), or a
bytes
object (for all other non-multipart types). Raise a
KeyError
if called on a
multipart
. If the part is a
text
part and
errors
is specified, use it as the error handler when decoding the payload to unicode. The default error handler is
replace
.
email.contentmanager.
set_content
(
msg
,
<'str'>
,
subtype="plain"
,
charset='utf-8' cte=None
,
disposition=None
,
filename=None
,
cid=None
,
params=None
,
headers=None
)
¶
email.contentmanager.
set_content
(
msg
,
<'bytes'>
,
maintype
,
subtype
,
cte="base64"
,
disposition=None
,
filename=None
,
cid=None
,
params=None
,
headers=None
)
email.contentmanager.
set_content
(
msg
,
<'Message'>
,
cte=None
,
disposition=None
,
filename=None
,
cid=None
,
params=None
,
headers=None
)
email.contentmanager.
set_content
(
msg
,
<'list'>
,
subtype='mixed'
,
disposition=None
,
filename=None
,
cid=None
,
params=None
,
headers=None
)
Add headers and payload to msg :
添加
Content-Type
头采用
maintype/subtype
值。
str
,设置 MIME
maintype
to
text
, and set the
subtype to
subtype
if it is specified, or
plain
if it is not.
bytes
, use the specified
maintype
and
subtype
,或
引发
TypeError
if they are not specified.
Message
objects, set the maintype to
message
, and set the subtype to
subtype
if it is specified
or
rfc822
if it is not. If
subtype
is
partial
, raise an
error (
bytes
objects must be used to construct
message/partial
parts).
Message
objects, set the
maintype
to
multipart
,和
subtype
to
subtype
if it is
specified, and
mixed
if it is not. If the message parts in
the
<’list’>
have
MIME-Version
headers, remove
them.
若
charset
is provided (which is valid only for
str
), encode the string to bytes using the specified character set. The default is
utf-8
。若指定
charset
is a known alias for a standard MIME charset name, use the standard charset instead.
若
cte
is set, encode the payload using the specified content transfer encoding, and set the
Content-Transfer-Endcoding
header to that value. For
str
objects, if it is not set use heuristics to determine the most compact encoding. Possible values for
cte
are
quoted-printable
,
base64
,
7bit
,
8bit
,和
binary
. If the input cannot be encoded in the specified encoding (eg:
7bit
), raise a
ValueError
。对于
Message
, per
RFC 2046
, raise an error if a
cte
of
quoted-printable
or
base64
is requested for
subtype
rfc822
, and for any
cte
除了
7bit
for
subtype
external-body
。对于
message/rfc822
,使用
8bit
if
cte
is not specified. For all other values of
subtype
,使用
7bit
.
注意
A
cte
of
binary
does not actually work correctly yet. The
Message
object as modified by
set_content
is correct, but
BytesGenerator
does not serialize it correctly.
若
disposition
is set, use it as the value of the
Content-Disposition
header. If not specified, and
filename
is specified, add the header with the value
attachment
. If it is not specified and
filename
is also not specified, do not add the header. The only valid values for
disposition
are
attachment
and
inline
.
若
filename
is specified, use it as the value of the
filename
参数为
Content-Disposition
header. There is no default.
若 cid is specified, add a Content-ID header with cid as its value.
若
params
is specified, iterate its
items
method and use the resulting
(key, value)
pairs to set additional parameters on the
Content-Type
头。
若
headers
is specified and is a list of strings of the form
headername: headervalue
或列表化的
header
objects (distinguised from strings by having a
name
attribute), add the headers to
msg
.