blob: f7eb471f330196be009891621504e04c750c2481 [file] [log] [blame]
R David Murray3edd22a2011-04-18 13:59:37 -04001:mod:`email`: Policy Objects
2----------------------------
3
4.. module:: email.policy
5 :synopsis: Controlling the parsing and generating of messages
6
7
8The :mod:`email` package's prime focus is the handling of email messages as
9described by the various email and MIME RFCs. However, the general format of
10email messages (a block of header fields each consisting of a name followed by
11a colon followed by a value, the whole block followed by a blank line and an
12arbitrary 'body'), is a format that has found utility outside of the realm of
13email. Some of these uses conform fairly closely to the main RFCs, some do
14not. And even when working with email, there are times when it is desirable to
15break strict compliance with the RFCs.
16
17Policy objects are the mechanism used to provide the email package with the
18flexibility to handle all these disparate use cases,
19
20A :class:`Policy` object encapsulates a set of attributes and methods that
21control the behavior of various components of the email package during use.
22:class:`Policy` instances can be passed to various classes and methods in the
23email package to alter the default behavior. The settable values and their
24defaults are described below. The :mod:`policy` module also provides some
25pre-created :class:`Policy` instances. In addition to a :const:`default`
26instance, there are instances tailored for certain applications. For example
27there is an :const:`SMTP` :class:`Policy` with defaults appropriate for
28generating output to be sent to an SMTP server. These are listed :ref:`below
29<Policy Instances>`.
30
31In general an application will only need to deal with setting the policy at the
32input and output boundaries. Once parsed, a message is represented by a
33:class:`~email.message.Message` object, which is designed to be independent of
34the format that the message has "on the wire" when it is received, transmitted,
35or displayed. Thus, a :class:`Policy` can be specified when parsing a message
36to create a :class:`~email.message.Message`, and again when turning the
37:class:`~email.message.Message` into some other representation. While often a
38program will use the same :class:`Policy` for both input and output, the two
39can be different.
40
41As an example, the following code could be used to read an email message from a
42file on disk and pass it to the system ``sendmail`` program on a ``unix``
43system::
44
45 >>> from email import msg_from_binary_file
46 >>> from email.generator import BytesGenerator
47 >>> import email.policy
48 >>> from subprocess import Popen, PIPE
49 >>> with open('mymsg.txt', 'b') as f:
50 >>> msg = msg_from_binary_file(f, policy=email.policy.mbox)
51 >>> p = Popen(['sendmail', msg['To'][0].address], stdin=PIPE)
52 >>> g = BytesGenerator(p.stdin, email.policy.policy=SMTP)
53 >>> g.flatten(msg)
54 >>> p.stdin.close()
55 >>> rc = p.wait()
56
57Some email package methods accept a *policy* keyword argument, allowing the
58policy to be overridden for that method. For example, the following code use
59the :meth:`email.message.Message.as_string` method to the *msg* object from the
60previous example and re-write it to a file using the native line separators for
61the platform on which it is running::
62
63 >>> import os
64 >>> mypolicy = email.policy.Policy(linesep=os.linesep)
65 >>> with open('converted.txt', 'wb') as f:
66 ... f.write(msg.as_string(policy=mypolicy))
67
68Policy instances are immutable, but they can be cloned, accepting the same
69keyword arguments as the class constructor and returning a new :class:`Policy`
70instance that is a copy of the original but with the specified attributes
71values changed. For example, the following creates an SMTP policy that will
72raise any defects detected as errors::
73
74 >>> strict_SMTP = email.policy.SMTP.clone(raise_on_defect=True)
75
76Policy objects can also be combined using the addition operator, producing a
77policy object whose settings are a combination of the non-default values of the
78summed objects::
79
80 >>> strict_SMTP = email.policy.SMTP + email.policy.strict
81
82This operation is not commutative; that is, the order in which the objects are
83added matters. To illustrate::
84
85 >>> Policy = email.policy.Policy
86 >>> apolicy = Policy(max_line_length=100) + Policy(max_line_length=80)
87 >>> apolicy.max_line_length
88 80
89 >>> apolicy = Policy(max_line_length=80) + Policy(max_line_length=100)
90 >>> apolicy.max_line_length
91 100
92
93
94.. class:: Policy(**kw)
95
96 The valid constructor keyword arguments are any of the attributes listed
97 below.
98
99 .. attribute:: max_line_length
100
101 The maximum length of any line in the serialized output, not counting the
102 end of line character(s). Default is 78, per :rfc:`5322`. A value of
103 ``0`` or :const:`None` indicates that no line wrapping should be
104 done at all.
105
106 .. attribute:: linesep
107
108 The string to be used to terminate lines in serialized output. The
109 default is '\\n' because that's the internal end-of-line discipline used
110 by Python, though '\\r\\n' is required by the RFCs. See `Policy
111 Instances`_ for policies that use an RFC conformant linesep. Setting it
112 to :attr:`os.linesep` may also be useful.
113
114 .. attribute:: must_be_7bit
115
116 If :const:`True`, data output by a bytes generator is limited to ASCII
117 characters. If :const:`False` (the default), then bytes with the high
118 bit set are preserved and/or allowed in certain contexts (for example,
119 where possible a content transfer encoding of ``8bit`` will be used).
120 String generators act as if ``must_be_7bit`` is `True` regardless of the
121 policy in effect, since a string cannot represent non-ASCII bytes.
122
123 .. attribute:: raise_on_defect
124
125 If :const:`True`, any defects encountered will be raised as errors. If
126 :const:`False` (the default), defects will be passed to the
127 :meth:`register_defect` method.
128
129 .. method:: handle_defect(obj, defect)
130
131 *obj* is the object on which to register the defect. *defect* should be
132 an instance of a subclass of :class:`~email.errors.Defect`.
133 If :attr:`raise_on_defect`
134 is ``True`` the defect is raised as an exception. Otherwise *obj* and
135 *defect* are passed to :meth:`register_defect`. This method is intended
136 to be called by parsers when they encounter defects, and will not be
137 called by code that uses the email library unless that code is
138 implementing an alternate parser.
139
140 .. method:: register_defect(obj, defect)
141
142 *obj* is the object on which to register the defect. *defect* should be
143 a subclass of :class:`~email.errors.Defect`. This method is part of the
144 public API so that custom ``Policy`` subclasses can implement alternate
145 handling of defects. The default implementation calls the ``append``
146 method of the ``defects`` attribute of *obj*.
147
148 .. method:: clone(obj, *kw):
149
150 Return a new :class:`Policy` instance whose attributes have the same
151 values as the current instance, except where those attributes are
152 given new values by the keyword arguments.
153
154
155Policy Instances
156................
157
158The following instances of :class:`Policy` provide defaults suitable for
159specific common application domains.
160
161.. data:: default
162
163 An instance of :class:`Policy` with all defaults unchanged.
164
165.. data:: SMTP
166
167 Output serialized from a message will conform to the email and SMTP
168 RFCs. The only changed attribute is :attr:`linesep`, which is set to
169 ``\r\n``.
170
171.. data:: HTTP
172
173 Suitable for use when serializing headers for use in HTTP traffic.
174 :attr:`linesep` is set to ``\r\n``, and :attr:`max_line_length` is set to
175 :const:`None` (unlimited).
176
177.. data:: strict
178
179 :attr:`raise_on_defect` is set to :const:`True`.