email.contentmanager:管理 MIME 內容

原始碼:Lib/email/contentmanager.py


在 3.6 版被加入:[1]

classemail.contentmanager.ContentManager

Base class for content managers. Provides the standard registry mechanismsto register converters between MIME content and other representations, aswell as theget_content andset_content dispatch methods.

get_content(msg,*args,**kw)

Look up a handler function based on themimetype ofmsg (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 themaintype

  • the empty string

If none of these keys produce a handler, raise aKeyError for thefull MIME type.

set_content(msg,obj,*args,**kw)

If themaintype ismultipart, 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'squalname (typ.__qualname__)

  • the type'sname (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 aKeyError for the fullyqualified name of the type.

Also add aMIME-Version header if one is not present (seealsoMIMEPart).

add_get_handler(key,handler)

Record the functionhandler as the handler forkey. For the possiblevalues ofkey, seeget_content().

add_set_handler(typekey,handler)

Recordhandler as the function to call when an object of a typematchingtypekey is passed toset_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 providedbyMessage itself: it deals only with text, rawbyte strings, andMessage objects. Nevertheless, itprovides significant advantages compared to the base API:get_content ona text part will return a unicode string without the application needing tomanually decode it,set_content provides 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 (fortext parts), anEmailMessage object (formessage/rfc822parts), or abytes object (for all other non-multipart types). RaiseaKeyError if called on amultipart. If the part is atext part 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 amaintype/subtypevalue.

  • Forstr, set the MIMEmaintype totext, and set thesubtype tosubtype if it is specified, orplain if it is not.

  • Forbytes, use the specifiedmaintype andsubtype, orraise aTypeError if they are not specified.

  • ForEmailMessage objects, set the maintypetomessage, and set the subtype tosubtype if it isspecified orrfc822 if it is not. Ifsubtype ispartial, raise an error (bytes objects must be used toconstructmessage/partial parts).

Ifcharset is provided (which is valid only forstr), 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 arequoted-printable,base64,7bit,8bit, andbinary. If the input cannot beencoded in the specified encoding (for example, specifying acte of7bit for an input that contains non-ASCII values), raise aValueError.

  • Forstr objects, ifcte is not set use heuristics todetermine the most compact encoding. Prior to encoding,str.splitlines() is used to normalize all line boundaries,ensuring that each line of the payload is terminated by thecurrent policy'slinesep property(even if the original string did not end with one).

  • Forbytes objects,cte is taken to be base64 if not set,and the aforementioned newline translation is not performed.

  • ForEmailMessage, perRFC 2046, raisean error if acte ofquoted-printable orbase64 isrequested forsubtyperfc822, and for anycte other than7bit forsubtypeexternal-body. Formessage/rfc822, use8bit ifcte is not specified. Forall other values ofsubtype, use7bit.

備註

Acte ofbinary does not actually work correctly yet.TheEmailMessage object as modified byset_content iscorrect, butBytesGenerator does 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 valueattachment.Ifdisposition is not specified andfilename is also not specified,do not add the header. The only valid values fordisposition areattachment andinline.

Iffilename is specified, use it as the value of thefilenameparameter of theContent-Disposition header.

Ifcid is specified, add aContent-ID header withcid as its value.

Ifparams is specified, iterate itsitems method 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 formheadername:headervalue or a list ofheader objects(distinguished from strings by having aname attribute), add theheaders tomsg.

註解

[1]

Originally added in 3.4 as aprovisional module