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