email: Policy Objects

The email module’s prime focus is the handling of email messages as described by the various email and MIME RFCs. However, the general format of email messages (a block of header fields each consisting of a name followed by a colon followed by a value, the whole block followed by a blank line and an arbitrary ‘body’), is a format that has found utility outside of the realm of email. Some of these uses hew closely to the main RFCs, some do not. And even when working with email, there are times when it is desirable to break strict compliance with the RFCs.

Policy Objects are the mechanism used to provide the email package with the flexibility to handle all these disparate use cases,

A policy object encapsulates a set of attributes and methods that control the behavior of the various components of the email package during use. There are two base classes for policy objects: Policy and PolicySet. Policy provides a constructor that allows the setting of policy attributes via keyword arguments, but no default values or default method implementations. PolicySet provides a full set of default values and method implementations.

Almost every object created by the email package will have an associated policy attribute, which should be a PolicySet instance. When an application wishes to change the default policy for all objects it creates, it can create an instance of PolicySet (or of a subclass of it) with the non-default attribute values overridden, and use that to initialize the policy attribute of the objects it creates. For the most part the setting of the policy attribute on sub-objects happens automatically during the construction of a message, so in practice this means that the application-specific default policy needs to be passed to the message class constructor.

Many of the email package object methods accept a policy keyword-only argument. Under most circumstances the correct thing to pass to this argument is an instance of Policy (or of a subclass of it). Any attributes (or methods for a subclass) present on the Policy instance will override those from the object’s default policy.

Objects in the email package that have a policy attribute also have a policy_override attribute. This attribute is usually None, but can contain (or be set to) an object derived from Policy. Any attributes or methods on the policy_override object will override the corresponding attributes from the default policy. Certain object types use this to override certain defaults[1]. This mechanism can also be used by an application to set overrides on objects before attaching them to other objects (for example, setting an override on a header object before passing it to a message’s set_header() method).

If an application wants to ignore all policy_overrides during a given method call, it can pass a PolicySet-derived instance to the object’s method. Since the PolicySet defines all attributes and methods, none will be referred to the default policy on the object, and the object’s object-specific defaults will be ignored. (Note that this is is a very rare use case.)

In addition to the base classes already mentioned, the module provides a number of convenience subclasses for commonly used default policy overrides. These classes are subclasses of Policy. To use them as default policies, pass them to the constructor of a PolicySet class, which will copy the values of the attributes (they have no methods). Policy objects can also be composed in the same way; for example, a strict SMTP policy can be created by doing SMTP(Strict()) or Strict(SMTP()).

class email.policy.Policy(policy_overlay=None, **kw)

If an object is passed in as policy_overlay, it will be checked for any of the attributes listed for PolicySet, and if the attribute exists its value will be used as the value of that attribute for the Policy instance returned by the constructor.

The valid constructor keyword arguments are any of the attributes listed in policy_attributes, which is any of the attributes documented in PolicySet, below. If an attribute occurs both on the policy_overlay object and as a keyword argument, the keyword argument takes precedence.

policy_attributes
A list of the names of the public API attributes. These are the attributes whose values will be copied from a policy_overlay object.
default_policy(policy)
Use policy as the source of default policy. Any attributes not defined on the class or in the constructor will be delegated to this object. (This method is used internally to implement the policy_override behavior as well as the behavior when passing a policy to a method. It is exposed as part of the API in case a subclass wants to override it.)
class email.policy.PolicySet(policy_overlay=None, **kw)

If an object is passed in as policy_overlay, it will be checked for any of the attributes listed below, and if the attribute exists its value will be used as the value of that attribute for the PolicySet instance returned by the constructor.

The valid constructor keyword arguments are any of the attributes listed in policy_attributes, which is any of the attributes documented below. If an attribute occurs both on the policy_overlay object and as a keyword argument, the keyword argument takes precedence.

policy_attributes
A list of the names of the public API attributes. These are the attributes whose values will be copied from a policy_overlay object.
max_line_length
The maximum length of any line in the serialized output, not counting the end of line character(s). Default is 78, per RFC 5322. A value of 0 or None indicates that no line wrapping should be done at all.
newline
The string to be used to terminate lines in serialized output. The default is ‘\n’ because that’s the internal end-of-line discipline used by Python, though ‘\r\n’ is required by the RFCs. See the convenience policy objects for policies that use RFC conformant newlines. Setting it to os.linesep may also be useful.
use_raw_data_if_possible
If True, then, during serialization, if an object has raw data that raw data will be split into lines via splitlines() and emitted. If False (the default), the data will be transformed and wrapped as necessary to conform to max_line_length.
must_be_7bit

This policy attribute affects only bytes objects.

If True, data output by serialize is limited to ASCII characters. If False (the default), then bytes with the high bit set are allowed in certain contexts (for example, where possible a content transfer encoding of 8bit will be used).

header_indent
A string used to prefix all lines after the first when folding message headers. To be RFC compliant this may be composed only of spaces and/or tabs. The default is eight spaces.
raise_on_defect
If True, any defects encountered will be raised as errors. If False (the default), defects will be passed to the register_defect() method.
headers
A mapping from case insensitive header names to header classes. Three keys are special: __baseclass__ holds the class that will be used as the base class for all headers, and that will be used as the class for headers whose names do not appear in the registry. The default registry provides UnstructuredHeader for this key. __stringclass__ holds the class that will be mixed in to all headers whose source data is of type string. The default registry provides StringHeaderMixin for this key. __bytesclass__ holds the class that will be mixed in to all headers whose source data is of type bytes. The default registry provides BygesHeaderMixin for this key.
ctes
A mapping from RFC 2047 content transfer encoding codes to Coder classes. The default registry provides mappings for ‘q’ (quoted printable) and ‘b’ (base64) CTEs.
default_policy(policy)
This method is a non-operation, and is provided so that a PolicySet can be passed as a policy override in a method call.
handle_defect(obj, defect)
obj is the object on which the defect is detected. defect should be a subclass of Defect. If raise_on_defect is True defect is raised as an error. Otherwise register_defect() is called with the object and defect.
register_defect(obj, defect)
obj is the object on which the defect is detected. defect should be a subclass of Defect. The defect is appended to obj‘s defects attribute.

Domain Specific Policies

These are subclasses of Policy.

SMTP

Output serialized from a bytes message will conform to the email and SMTP RFCs. The only changed attribute is newline, which is set to ‘\r\n’.

HTTP

Suitable for use when serializing headers for use in HTTP traffic. newline is set to ‘\r\n’, and max_line_length is set to None (unlimited).

Strict

raise_on_defect is set to True.

Footnotes

[1]For example, the MIME signed message object will set the use_raw_data_if_possible policy attribute to True, so that the original data is preserved, as required by RFC 1847, even if the policy otherwise calls for rewrapping lines (as PolicySet does by default).