email.contentmanager: Managing MIME Content¶
Source code:Lib/email/contentmanager.py
New in version 3.6:1
- class
email.contentmanager.ContentManager¶ Base class for content managers. Provides the standard registry mechanismsto register converters between MIME content and other representations, aswell as the
get_contentandset_contentdispatch methods.get_content(msg,*args,**kw)¶Look up a handler function based on the
mimetypeofmsg (see nextparagraph), call it, passing through all arguments, and return the resultof the call. The expectation is that the handler will extract thepayload frommsg and return an object that encodes information aboutthe extracted data.To find the handler, look for the following keys in the registry,stopping with the first one found:
the string representing the full MIME type (
maintype/subtype)the string representing the
maintypethe empty string
If none of these keys produce a handler, raise a
KeyErrorfor thefull MIME type.
set_content(msg,obj,*args,**kw)¶If the
maintypeismultipart, raise aTypeError; otherwiselook up a handler function based on the type ofobj (see nextparagraph), callclear_content()on themsg, and call the handler function, passing through all arguments. Theexpectation is that the handler will transform and storeobj intomsg, possibly making other changes tomsg as well, such as addingvarious MIME headers to encode information needed to interpret the storeddata.To find the handler, obtain the type ofobj (
typ=type(obj)), andlook for the following keys in the registry, stopping with the first onefound:the type itself (
typ)the type’s fully qualified name (
typ.__module__+'.'+typ.__qualname__).the type’s qualname (
typ.__qualname__)the type’s name (
typ.__name__).
If none of the above match, repeat all of the checks above for each ofthe types in theMRO (
typ.__mro__). Finally, if no other keyyields a handler, check for a handler for the keyNone. If there isno handler forNone, raise aKeyErrorfor the fullyqualified name of the type.Also add aMIME-Version header if one is not present (seealso
MIMEPart).
add_get_handler(key,handler)¶Record the functionhandler as the handler forkey. For the possiblevalues ofkey, see
get_content().
add_set_handler(typekey,handler)¶Recordhandler as the function to call when an object of a typematchingtypekey is passed to
set_content(). For the possiblevalues oftypekey, seeset_content().
Content Manager Instances¶
Currently the email package provides only one concrete content manager,raw_data_manager, although more may be added in the future.raw_data_manager is thecontent_manager provided byEmailPolicy and its derivatives.
email.contentmanager.raw_data_manager¶This content manager provides only a minimum interface beyond that providedby
Messageitself: it deals only with text, rawbyte strings, andMessageobjects. Nevertheless, itprovides significant advantages compared to the base API:get_contentona text part will return a unicode string without the application needing tomanually decode it,set_contentprovides a rich set of options forcontrolling the headers added to a part and controlling the content transferencoding, and it enables the use of the variousadd_methods, therebysimplifying the creation of multipart messages.email.contentmanager.get_content(msg,errors='replace')¶Return the payload of the part as either a string (for
textparts), anEmailMessageobject (formessage/rfc822parts), or abytesobject (for all other non-multipart types). RaiseaKeyErrorif called on amultipart. If the part is atextpart anderrors is specified, use it as the error handler whendecoding the payload to unicode. The default error handler isreplace.
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,<'EmailMessage'>,cte=None,disposition=None,filename=None,cid=None,params=None,headers=None)Add headers and payload tomsg:
Add aContent-Type header with a
maintype/subtypevalue.For
str, set the MIMEmaintypetotext, and set thesubtype tosubtype if it is specified, orplainif it is not.For
bytes, use the specifiedmaintype andsubtype, orraise aTypeErrorif they are not specified.For
EmailMessageobjects, set the maintypetomessage, and set the subtype tosubtype if it isspecified orrfc822if it is not. Ifsubtype ispartial, raise an error (bytesobjects must be used toconstructmessage/partialparts).
Ifcharset is provided (which is valid only for
str), encode thestring to bytes using the specified character set. The default isutf-8. If the specifiedcharset is a known alias for a standardMIME charset name, use the standard charset instead.Ifcte is set, encode the payload using the specified content transferencoding, and set theContent-Transfer-Encoding header tothat value. Possible values forcte are
quoted-printable,base64,7bit,8bit, andbinary. If the input cannot beencoded in the specified encoding (for example, specifying acte of7bitfor an input that contains non-ASCII values), raise aValueError.For
strobjects, ifcte is not set use heuristics todetermine the most compact encoding.For
EmailMessage, perRFC 2046, raisean error if acte ofquoted-printableorbase64isrequested forsubtyperfc822, and for anycte other than7bitforsubtypeexternal-body. Formessage/rfc822, use8bitifcte is not specified. Forall other values ofsubtype, use7bit.
Note
Acte of
binarydoes not actually work correctly yet.TheEmailMessageobject as modified byset_contentiscorrect, butBytesGeneratordoes notserialize it correctly.Ifdisposition is set, use it as the value of theContent-Disposition header. If not specified, andfilename is specified, add the header with the value
attachment.Ifdisposition is not specified andfilename is also not specified,do not add the header. The only valid values fordisposition areattachmentandinline.Iffilename is specified, use it as the value of the
filenameparameter of theContent-Disposition header.Ifcid is specified, add aContent-ID header withcid as its value.
Ifparams is specified, iterate its
itemsmethod and use theresulting(key,value)pairs to set additional parameters on theContent-Type header.Ifheaders is specified and is a list of strings of the form
headername:headervalueor a list ofheaderobjects(distinguished from strings by having anameattribute), add theheaders tomsg.
Footnotes
- 1
Originally added in 3.4 as aprovisional module