blob: 0d6c27ac5e8954fbadf77d4d54790b1ff2b7105b [file] [log] [blame]
R David Murray79cf3ba2012-05-27 17:10:36 -04001:mod:`email.policy`: Policy Objects
2-----------------------------------
R David Murray3edd22a2011-04-18 13:59:37 -04003
4.. module:: email.policy
5 :synopsis: Controlling the parsing and generating of messages
6
R David Murray79cf3ba2012-05-27 17:10:36 -04007.. moduleauthor:: R. David Murray <rdmurray@bitdance.com>
8.. sectionauthor:: R. David Murray <rdmurray@bitdance.com>
9
Éric Araujo54dbfbd2011-08-10 21:43:13 +020010.. versionadded:: 3.3
R David Murray6a45d3b2011-04-18 16:00:47 -040011
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040012**Source code:** :source:`Lib/email/policy.py`
13
14--------------
R David Murray3edd22a2011-04-18 13:59:37 -040015
16The :mod:`email` package's prime focus is the handling of email messages as
17described by the various email and MIME RFCs. However, the general format of
18email messages (a block of header fields each consisting of a name followed by
19a colon followed by a value, the whole block followed by a blank line and an
20arbitrary 'body'), is a format that has found utility outside of the realm of
R David Murray29d1bc02016-09-07 21:15:59 -040021email. Some of these uses conform fairly closely to the main email RFCs, some
22do not. Even when working with email, there are times when it is desirable to
23break strict compliance with the RFCs, such as generating emails that
24interoperate with email servers that do not themselves follow the standards, or
25that implement extensions you want to use in ways that violate the
26standards.
R David Murray3edd22a2011-04-18 13:59:37 -040027
R David Murray6a45d3b2011-04-18 16:00:47 -040028Policy objects give the email package the flexibility to handle all these
29disparate use cases.
R David Murray3edd22a2011-04-18 13:59:37 -040030
31A :class:`Policy` object encapsulates a set of attributes and methods that
32control the behavior of various components of the email package during use.
33:class:`Policy` instances can be passed to various classes and methods in the
34email package to alter the default behavior. The settable values and their
R David Murrayc27e5222012-05-25 15:01:48 -040035defaults are described below.
R David Murray3edd22a2011-04-18 13:59:37 -040036
R David Murray29d1bc02016-09-07 21:15:59 -040037There is a default policy used by all classes in the email package. For all of
38the :mod:`~email.parser` classes and the related convenience functions, and for
39the :class:`~email.message.Message` class, this is the :class:`Compat32`
40policy, via its corresponding pre-defined instance :const:`compat32`. This
41policy provides for complete backward compatibility (in some cases, including
42bug compatibility) with the pre-Python3.3 version of the email package.
43
44This default value for the *policy* keyword to
45:class:`~email.message.EmailMessage` is the :class:`EmailPolicy` policy, via
46its pre-defined instance :data:`~default`.
47
48When a :class:`~email.message.Message` or :class:`~email.message.EmailMessage`
49object is created, it acquires a policy. If the message is created by a
50:mod:`~email.parser`, a policy passed to the parser will be the policy used by
51the message it creates. If the message is created by the program, then the
52policy can be specified when it is created. When a message is passed to a
53:mod:`~email.generator`, the generator uses the policy from the message by
54default, but you can also pass a specific policy to the generator that will
55override the one stored on the message object.
56
57The default value for the *policy* keyword for the :mod:`email.parser` classes
58and the parser convenience functions **will be changing** in a future version of
59Python. Therefore you should **always specify explicitly which policy you want
60to use** when calling any of the classes and functions described in the
61:mod:`~email.parser` module.
R David Murrayc27e5222012-05-25 15:01:48 -040062
63The first part of this documentation covers the features of :class:`Policy`, an
R David Murray29d1bc02016-09-07 21:15:59 -040064:term:`abstract base class` that defines the features that are common to all
R David Murrayc27e5222012-05-25 15:01:48 -040065policy objects, including :const:`compat32`. This includes certain hook
66methods that are called internally by the email package, which a custom policy
R David Murray29d1bc02016-09-07 21:15:59 -040067could override to obtain different behavior. The second part describes the
68concrete classes :class:`EmailPolicy` and :class:`Compat32`, which implement
69the hooks that provide the standard behavior and the backward compatible
70behavior and features, respectively.
R David Murrayc27e5222012-05-25 15:01:48 -040071
72:class:`Policy` instances are immutable, but they can be cloned, accepting the
73same keyword arguments as the class constructor and returning a new
74:class:`Policy` instance that is a copy of the original but with the specified
75attributes values changed.
R David Murray3edd22a2011-04-18 13:59:37 -040076
77As an example, the following code could be used to read an email message from a
R David Murrayfdfb0052013-07-29 15:49:58 -040078file on disk and pass it to the system ``sendmail`` program on a Unix system:
R David Murray3edd22a2011-04-18 13:59:37 -040079
R David Murrayfdfb0052013-07-29 15:49:58 -040080.. testsetup::
81
Zachary Ware640b1ca2016-08-10 00:39:41 -050082 from unittest import mock
83 mocker = mock.patch('subprocess.Popen')
84 m = mocker.start()
85 proc = mock.MagicMock()
86 m.return_value = proc
87 proc.stdin.close.return_value = None
88 mymsg = open('mymsg.txt', 'w')
89 mymsg.write('To: abc@xyz.com\n\n')
90 mymsg.flush()
R David Murrayfdfb0052013-07-29 15:49:58 -040091
92.. doctest::
93
94 >>> from email import message_from_binary_file
R David Murray3edd22a2011-04-18 13:59:37 -040095 >>> from email.generator import BytesGenerator
R David Murrayfdfb0052013-07-29 15:49:58 -040096 >>> from email import policy
R David Murray3edd22a2011-04-18 13:59:37 -040097 >>> from subprocess import Popen, PIPE
R David Murrayfdfb0052013-07-29 15:49:58 -040098 >>> with open('mymsg.txt', 'rb') as f:
99 ... msg = message_from_binary_file(f, policy=policy.default)
100 >>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)
R David Murrayc27e5222012-05-25 15:01:48 -0400101 >>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n'))
R David Murray3edd22a2011-04-18 13:59:37 -0400102 >>> g.flatten(msg)
103 >>> p.stdin.close()
104 >>> rc = p.wait()
105
Zachary Ware640b1ca2016-08-10 00:39:41 -0500106.. testcleanup::
R David Murrayfdfb0052013-07-29 15:49:58 -0400107
Zachary Ware640b1ca2016-08-10 00:39:41 -0500108 mymsg.close()
109 mocker.stop()
110 import os
111 os.remove('mymsg.txt')
R David Murrayfdfb0052013-07-29 15:49:58 -0400112
R David Murrayc27e5222012-05-25 15:01:48 -0400113Here we are telling :class:`~email.generator.BytesGenerator` to use the RFC
114correct line separator characters when creating the binary string to feed into
115``sendmail's`` ``stdin``, where the default policy would use ``\n`` line
116separators.
Éric Araujofe0472e2011-12-03 16:00:56 +0100117
R David Murray3edd22a2011-04-18 13:59:37 -0400118Some email package methods accept a *policy* keyword argument, allowing the
R David Murray6a45d3b2011-04-18 16:00:47 -0400119policy to be overridden for that method. For example, the following code uses
Barry Warsaw904c4812014-12-19 11:20:00 -0500120the :meth:`~email.message.Message.as_bytes` method of the *msg* object from
R David Murrayc27e5222012-05-25 15:01:48 -0400121the previous example and writes the message to a file using the native line
122separators for the platform on which it is running::
R David Murray3edd22a2011-04-18 13:59:37 -0400123
124 >>> import os
R David Murray3edd22a2011-04-18 13:59:37 -0400125 >>> with open('converted.txt', 'wb') as f:
R David Murraybb17d2b2013-08-09 16:15:28 -0400126 ... f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))
127 17
R David Murray3edd22a2011-04-18 13:59:37 -0400128
129Policy objects can also be combined using the addition operator, producing a
130policy object whose settings are a combination of the non-default values of the
131summed objects::
132
R David Murrayfdfb0052013-07-29 15:49:58 -0400133 >>> compat_SMTP = policy.compat32.clone(linesep='\r\n')
134 >>> compat_strict = policy.compat32.clone(raise_on_defect=True)
R David Murrayc27e5222012-05-25 15:01:48 -0400135 >>> compat_strict_SMTP = compat_SMTP + compat_strict
R David Murray3edd22a2011-04-18 13:59:37 -0400136
137This operation is not commutative; that is, the order in which the objects are
138added matters. To illustrate::
139
R David Murrayfdfb0052013-07-29 15:49:58 -0400140 >>> policy100 = policy.compat32.clone(max_line_length=100)
141 >>> policy80 = policy.compat32.clone(max_line_length=80)
142 >>> apolicy = policy100 + policy80
R David Murray3edd22a2011-04-18 13:59:37 -0400143 >>> apolicy.max_line_length
144 80
R David Murrayc27e5222012-05-25 15:01:48 -0400145 >>> apolicy = policy80 + policy100
R David Murray3edd22a2011-04-18 13:59:37 -0400146 >>> apolicy.max_line_length
147 100
148
149
150.. class:: Policy(**kw)
151
R David Murrayc27e5222012-05-25 15:01:48 -0400152 This is the :term:`abstract base class` for all policy classes. It provides
153 default implementations for a couple of trivial methods, as well as the
154 implementation of the immutability property, the :meth:`clone` method, and
155 the constructor semantics.
156
157 The constructor of a policy class can be passed various keyword arguments.
158 The arguments that may be specified are any non-method properties on this
159 class, plus any additional non-method properties on the concrete class. A
160 value specified in the constructor will override the default value for the
161 corresponding attribute.
162
163 This class defines the following properties, and thus values for the
164 following may be passed in the constructor of any policy class:
R David Murray3edd22a2011-04-18 13:59:37 -0400165
R David Murray29d1bc02016-09-07 21:15:59 -0400166
R David Murray3edd22a2011-04-18 13:59:37 -0400167 .. attribute:: max_line_length
168
169 The maximum length of any line in the serialized output, not counting the
170 end of line character(s). Default is 78, per :rfc:`5322`. A value of
171 ``0`` or :const:`None` indicates that no line wrapping should be
172 done at all.
173
R David Murray29d1bc02016-09-07 21:15:59 -0400174
R David Murray3edd22a2011-04-18 13:59:37 -0400175 .. attribute:: linesep
176
177 The string to be used to terminate lines in serialized output. The
R David Murray6a45d3b2011-04-18 16:00:47 -0400178 default is ``\n`` because that's the internal end-of-line discipline used
R David Murrayc27e5222012-05-25 15:01:48 -0400179 by Python, though ``\r\n`` is required by the RFCs.
R David Murray3edd22a2011-04-18 13:59:37 -0400180
R David Murray29d1bc02016-09-07 21:15:59 -0400181
R David Murrayc27e5222012-05-25 15:01:48 -0400182 .. attribute:: cte_type
R David Murray3edd22a2011-04-18 13:59:37 -0400183
R David Murrayc27e5222012-05-25 15:01:48 -0400184 Controls the type of Content Transfer Encodings that may be or are
185 required to be used. The possible values are:
186
Georg Brandl44ea77b2013-03-28 13:28:44 +0100187 .. tabularcolumns:: |l|L|
188
R David Murrayc27e5222012-05-25 15:01:48 -0400189 ======== ===============================================================
190 ``7bit`` all data must be "7 bit clean" (ASCII-only). This means that
191 where necessary data will be encoded using either
192 quoted-printable or base64 encoding.
193
194 ``8bit`` data is not constrained to be 7 bit clean. Data in headers is
195 still required to be ASCII-only and so will be encoded (see
R David Murray29d1bc02016-09-07 21:15:59 -0400196 :meth:`fold_binary` and :attr:`~EmailPolicy.utf8` below for
197 exceptions), but body parts may use the ``8bit`` CTE.
R David Murrayc27e5222012-05-25 15:01:48 -0400198 ======== ===============================================================
199
200 A ``cte_type`` value of ``8bit`` only works with ``BytesGenerator``, not
201 ``Generator``, because strings cannot contain binary data. If a
202 ``Generator`` is operating under a policy that specifies
203 ``cte_type=8bit``, it will act as if ``cte_type`` is ``7bit``.
R David Murray3edd22a2011-04-18 13:59:37 -0400204
R David Murray29d1bc02016-09-07 21:15:59 -0400205
R David Murray3edd22a2011-04-18 13:59:37 -0400206 .. attribute:: raise_on_defect
207
208 If :const:`True`, any defects encountered will be raised as errors. If
209 :const:`False` (the default), defects will be passed to the
210 :meth:`register_defect` method.
211
R David Murrayfdb23c22015-05-17 14:24:33 -0400212
R David Murrayfdb23c22015-05-17 14:24:33 -0400213 .. attribute:: mangle_from\_
214
215 If :const:`True`, lines starting with *"From "* in the body are
216 escaped by putting a ``>`` in front of them. This parameter is used when
217 the message is being serialized by a generator.
218 Default: :const:`False`.
219
220 .. versionadded:: 3.5
221 The *mangle_from_* parameter.
222
R David Murray29d1bc02016-09-07 21:15:59 -0400223
R David Murrayc27e5222012-05-25 15:01:48 -0400224 The following :class:`Policy` method is intended to be called by code using
225 the email library to create policy instances with custom settings:
R David Murray6a45d3b2011-04-18 16:00:47 -0400226
R David Murray29d1bc02016-09-07 21:15:59 -0400227
R David Murrayc27e5222012-05-25 15:01:48 -0400228 .. method:: clone(**kw)
R David Murray3edd22a2011-04-18 13:59:37 -0400229
230 Return a new :class:`Policy` instance whose attributes have the same
231 values as the current instance, except where those attributes are
232 given new values by the keyword arguments.
233
R David Murray29d1bc02016-09-07 21:15:59 -0400234
R David Murrayc27e5222012-05-25 15:01:48 -0400235 The remaining :class:`Policy` methods are called by the email package code,
236 and are not intended to be called by an application using the email package.
237 A custom policy must implement all of these methods.
R David Murray3edd22a2011-04-18 13:59:37 -0400238
R David Murray29d1bc02016-09-07 21:15:59 -0400239
R David Murrayc27e5222012-05-25 15:01:48 -0400240 .. method:: handle_defect(obj, defect)
R David Murray3edd22a2011-04-18 13:59:37 -0400241
R David Murrayc27e5222012-05-25 15:01:48 -0400242 Handle a *defect* found on *obj*. When the email package calls this
243 method, *defect* will always be a subclass of
244 :class:`~email.errors.Defect`.
R David Murray3edd22a2011-04-18 13:59:37 -0400245
R David Murrayc27e5222012-05-25 15:01:48 -0400246 The default implementation checks the :attr:`raise_on_defect` flag. If
247 it is ``True``, *defect* is raised as an exception. If it is ``False``
248 (the default), *obj* and *defect* are passed to :meth:`register_defect`.
R David Murray3edd22a2011-04-18 13:59:37 -0400249
R David Murray29d1bc02016-09-07 21:15:59 -0400250
R David Murrayc27e5222012-05-25 15:01:48 -0400251 .. method:: register_defect(obj, defect)
R David Murray3edd22a2011-04-18 13:59:37 -0400252
R David Murrayc27e5222012-05-25 15:01:48 -0400253 Register a *defect* on *obj*. In the email package, *defect* will always
254 be a subclass of :class:`~email.errors.Defect`.
R David Murray3edd22a2011-04-18 13:59:37 -0400255
R David Murrayc27e5222012-05-25 15:01:48 -0400256 The default implementation calls the ``append`` method of the ``defects``
257 attribute of *obj*. When the email package calls :attr:`handle_defect`,
258 *obj* will normally have a ``defects`` attribute that has an ``append``
259 method. Custom object types used with the email package (for example,
260 custom ``Message`` objects) should also provide such an attribute,
261 otherwise defects in parsed messages will raise unexpected errors.
R David Murray3edd22a2011-04-18 13:59:37 -0400262
R David Murray29d1bc02016-09-07 21:15:59 -0400263
R David Murrayabfc3742012-05-29 09:14:44 -0400264 .. method:: header_max_count(name)
265
266 Return the maximum allowed number of headers named *name*.
267
R David Murray29d1bc02016-09-07 21:15:59 -0400268 Called when a header is added to an :class:`~email.message.EmailMessage`
269 or :class:`~email.message.Message` object. If the returned value is not
270 ``0`` or ``None``, and there are already a number of headers with the
271 name *name* greather than or equal to the value returned, a
272 :exc:`ValueError` is raised.
R David Murrayabfc3742012-05-29 09:14:44 -0400273
274 Because the default behavior of ``Message.__setitem__`` is to append the
275 value to the list of headers, it is easy to create duplicate headers
276 without realizing it. This method allows certain headers to be limited
277 in the number of instances of that header that may be added to a
278 ``Message`` programmatically. (The limit is not observed by the parser,
279 which will faithfully produce as many headers as exist in the message
280 being parsed.)
281
282 The default implementation returns ``None`` for all header names.
283
R David Murray29d1bc02016-09-07 21:15:59 -0400284
R David Murrayc27e5222012-05-25 15:01:48 -0400285 .. method:: header_source_parse(sourcelines)
R David Murray3edd22a2011-04-18 13:59:37 -0400286
R David Murrayc27e5222012-05-25 15:01:48 -0400287 The email package calls this method with a list of strings, each string
288 ending with the line separation characters found in the source being
289 parsed. The first line includes the field header name and separator.
290 All whitespace in the source is preserved. The method should return the
291 ``(name, value)`` tuple that is to be stored in the ``Message`` to
292 represent the parsed header.
R David Murray3edd22a2011-04-18 13:59:37 -0400293
R David Murrayc27e5222012-05-25 15:01:48 -0400294 If an implementation wishes to retain compatibility with the existing
295 email package policies, *name* should be the case preserved name (all
296 characters up to the '``:``' separator), while *value* should be the
297 unfolded value (all line separator characters removed, but whitespace
298 kept intact), stripped of leading whitespace.
R David Murray3edd22a2011-04-18 13:59:37 -0400299
R David Murrayc27e5222012-05-25 15:01:48 -0400300 *sourcelines* may contain surrogateescaped binary data.
301
302 There is no default implementation
303
R David Murray29d1bc02016-09-07 21:15:59 -0400304
R David Murrayc27e5222012-05-25 15:01:48 -0400305 .. method:: header_store_parse(name, value)
306
307 The email package calls this method with the name and value provided by
308 the application program when the application program is modifying a
309 ``Message`` programmatically (as opposed to a ``Message`` created by a
310 parser). The method should return the ``(name, value)`` tuple that is to
311 be stored in the ``Message`` to represent the header.
312
313 If an implementation wishes to retain compatibility with the existing
314 email package policies, the *name* and *value* should be strings or
315 string subclasses that do not change the content of the passed in
316 arguments.
317
318 There is no default implementation
319
R David Murray29d1bc02016-09-07 21:15:59 -0400320
R David Murrayc27e5222012-05-25 15:01:48 -0400321 .. method:: header_fetch_parse(name, value)
322
323 The email package calls this method with the *name* and *value* currently
324 stored in the ``Message`` when that header is requested by the
325 application program, and whatever the method returns is what is passed
326 back to the application as the value of the header being retrieved.
327 Note that there may be more than one header with the same name stored in
328 the ``Message``; the method is passed the specific name and value of the
329 header destined to be returned to the application.
330
331 *value* may contain surrogateescaped binary data. There should be no
332 surrogateescaped binary data in the value returned by the method.
333
334 There is no default implementation
335
R David Murray29d1bc02016-09-07 21:15:59 -0400336
R David Murrayc27e5222012-05-25 15:01:48 -0400337 .. method:: fold(name, value)
338
339 The email package calls this method with the *name* and *value* currently
340 stored in the ``Message`` for a given header. The method should return a
341 string that represents that header "folded" correctly (according to the
342 policy settings) by composing the *name* with the *value* and inserting
343 :attr:`linesep` characters at the appropriate places. See :rfc:`5322`
344 for a discussion of the rules for folding email headers.
345
346 *value* may contain surrogateescaped binary data. There should be no
347 surrogateescaped binary data in the string returned by the method.
348
R David Murray29d1bc02016-09-07 21:15:59 -0400349
R David Murrayc27e5222012-05-25 15:01:48 -0400350 .. method:: fold_binary(name, value)
351
352 The same as :meth:`fold`, except that the returned value should be a
353 bytes object rather than a string.
354
355 *value* may contain surrogateescaped binary data. These could be
356 converted back into binary data in the returned bytes object.
357
358
R David Murray0b6f6c82012-05-25 18:42:14 -0400359
360.. class:: EmailPolicy(**kw)
361
362 This concrete :class:`Policy` provides behavior that is intended to be fully
363 compliant with the current email RFCs. These include (but are not limited
364 to) :rfc:`5322`, :rfc:`2047`, and the current MIME RFCs.
365
366 This policy adds new header parsing and folding algorithms. Instead of
R David Murray3da240f2013-10-16 22:48:40 -0400367 simple strings, headers are ``str`` subclasses with attributes that depend
R David Murray0b6f6c82012-05-25 18:42:14 -0400368 on the type of the field. The parsing and folding algorithm fully implement
369 :rfc:`2047` and :rfc:`5322`.
370
371 In addition to the settable attributes listed above that apply to all
372 policies, this policy adds the following additional attributes:
373
R David Murray29d1bc02016-09-07 21:15:59 -0400374 .. versionadded:: 3.3 as a :term:`provisional feature <provisional package>`.
375
376 .. versionchanged:: 3.6 provisional status removed.
377
378
R David Murray224ef3e2015-05-17 11:29:21 -0400379 .. attribute:: utf8
380
381 If ``False``, follow :rfc:`5322`, supporting non-ASCII characters in
382 headers by encoding them as "encoded words". If ``True``, follow
383 :rfc:`6532` and use ``utf-8`` encoding for headers. Messages
384 formatted in this way may be passed to SMTP servers that support
385 the ``SMTPUTF8`` extension (:rfc:`6531`).
386
R David Murray29d1bc02016-09-07 21:15:59 -0400387
R David Murray0b6f6c82012-05-25 18:42:14 -0400388 .. attribute:: refold_source
389
390 If the value for a header in the ``Message`` object originated from a
391 :mod:`~email.parser` (as opposed to being set by a program), this
392 attribute indicates whether or not a generator should refold that value
R David Murray29d1bc02016-09-07 21:15:59 -0400393 when transforming the message back into serialized form. The possible
394 values are:
R David Murray0b6f6c82012-05-25 18:42:14 -0400395
396 ======== ===============================================================
397 ``none`` all source values use original folding
398
399 ``long`` source values that have any line that is longer than
400 ``max_line_length`` will be refolded
401
402 ``all`` all values are refolded.
403 ======== ===============================================================
404
405 The default is ``long``.
406
R David Murray29d1bc02016-09-07 21:15:59 -0400407
R David Murray0b6f6c82012-05-25 18:42:14 -0400408 .. attribute:: header_factory
409
410 A callable that takes two arguments, ``name`` and ``value``, where
411 ``name`` is a header field name and ``value`` is an unfolded header field
R David Murrayea976682012-05-27 15:03:38 -0400412 value, and returns a string subclass that represents that header. A
413 default ``header_factory`` (see :mod:`~email.headerregistry`) is provided
R David Murray29d1bc02016-09-07 21:15:59 -0400414 that supports custom parsing for the various address and date :RFC:`5322`
415 header field types, and the major MIME header field stypes. Support for
416 additional custom parsing will be added in the future.
417
R David Murray0b6f6c82012-05-25 18:42:14 -0400418
R David Murray3da240f2013-10-16 22:48:40 -0400419 .. attribute:: content_manager
420
421 An object with at least two methods: get_content and set_content. When
R David Murray29d1bc02016-09-07 21:15:59 -0400422 the :meth:`~email.message.EmailMessage.get_content` or
423 :meth:`~email.message.EmailMessage.set_content` method of an
424 :class:`~email.message.EmailMessage` object is called, it calls the
R David Murray3da240f2013-10-16 22:48:40 -0400425 corresponding method of this object, passing it the message object as its
426 first argument, and any arguments or keywords that were passed to it as
427 additional arguments. By default ``content_manager`` is set to
428 :data:`~email.contentmanager.raw_data_manager`.
429
Larry Hastings3732ed22014-03-15 21:13:56 -0700430 .. versionadded:: 3.4
R David Murray3da240f2013-10-16 22:48:40 -0400431
432
R David Murray0b6f6c82012-05-25 18:42:14 -0400433 The class provides the following concrete implementations of the abstract
434 methods of :class:`Policy`:
435
R David Murray29d1bc02016-09-07 21:15:59 -0400436
R David Murrayabfc3742012-05-29 09:14:44 -0400437 .. method:: header_max_count(name)
438
439 Returns the value of the
440 :attr:`~email.headerregistry.BaseHeader.max_count` attribute of the
441 specialized class used to represent the header with the given name.
442
R David Murray29d1bc02016-09-07 21:15:59 -0400443
R David Murray0b6f6c82012-05-25 18:42:14 -0400444 .. method:: header_source_parse(sourcelines)
445
R David Murray29d1bc02016-09-07 21:15:59 -0400446
447 The name is parsed as everything up to the '``:``' and returned
448 unmodified. The value is determined by stripping leading whitespace off
449 the remainder of the first line, joining all subsequent lines together,
450 and stripping any trailing carriage return or linefeed characters.
451
R David Murray0b6f6c82012-05-25 18:42:14 -0400452
453 .. method:: header_store_parse(name, value)
454
455 The name is returned unchanged. If the input value has a ``name``
456 attribute and it matches *name* ignoring case, the value is returned
457 unchanged. Otherwise the *name* and *value* are passed to
R David Murray3da240f2013-10-16 22:48:40 -0400458 ``header_factory``, and the resulting header object is returned as
R David Murray0b6f6c82012-05-25 18:42:14 -0400459 the value. In this case a ``ValueError`` is raised if the input value
460 contains CR or LF characters.
461
R David Murray29d1bc02016-09-07 21:15:59 -0400462
R David Murray0b6f6c82012-05-25 18:42:14 -0400463 .. method:: header_fetch_parse(name, value)
464
465 If the value has a ``name`` attribute, it is returned to unmodified.
466 Otherwise the *name*, and the *value* with any CR or LF characters
R David Murray3da240f2013-10-16 22:48:40 -0400467 removed, are passed to the ``header_factory``, and the resulting
R David Murray0b6f6c82012-05-25 18:42:14 -0400468 header object is returned. Any surrogateescaped bytes get turned into
469 the unicode unknown-character glyph.
470
R David Murray29d1bc02016-09-07 21:15:59 -0400471
R David Murray0b6f6c82012-05-25 18:42:14 -0400472 .. method:: fold(name, value)
473
474 Header folding is controlled by the :attr:`refold_source` policy setting.
475 A value is considered to be a 'source value' if and only if it does not
476 have a ``name`` attribute (having a ``name`` attribute means it is a
477 header object of some sort). If a source value needs to be refolded
R David Murray3da240f2013-10-16 22:48:40 -0400478 according to the policy, it is converted into a header object by
R David Murray0b6f6c82012-05-25 18:42:14 -0400479 passing the *name* and the *value* with any CR and LF characters removed
R David Murray3da240f2013-10-16 22:48:40 -0400480 to the ``header_factory``. Folding of a header object is done by
R David Murray0b6f6c82012-05-25 18:42:14 -0400481 calling its ``fold`` method with the current policy.
482
483 Source values are split into lines using :meth:`~str.splitlines`. If
484 the value is not to be refolded, the lines are rejoined using the
485 ``linesep`` from the policy and returned. The exception is lines
486 containing non-ascii binary data. In that case the value is refolded
487 regardless of the ``refold_source`` setting, which causes the binary data
488 to be CTE encoded using the ``unknown-8bit`` charset.
489
R David Murray29d1bc02016-09-07 21:15:59 -0400490
R David Murray0b6f6c82012-05-25 18:42:14 -0400491 .. method:: fold_binary(name, value)
492
Serhiy Storchakae0f0cf42013-08-19 09:59:18 +0300493 The same as :meth:`fold` if :attr:`~Policy.cte_type` is ``7bit``, except
494 that the returned value is bytes.
R David Murray0b6f6c82012-05-25 18:42:14 -0400495
Serhiy Storchakae0f0cf42013-08-19 09:59:18 +0300496 If :attr:`~Policy.cte_type` is ``8bit``, non-ASCII binary data is
497 converted back
R David Murray0b6f6c82012-05-25 18:42:14 -0400498 into bytes. Headers with binary data are not refolded, regardless of the
499 ``refold_header`` setting, since there is no way to know whether the
500 binary data consists of single byte characters or multibyte characters.
501
R David Murray29d1bc02016-09-07 21:15:59 -0400502
R David Murray0b6f6c82012-05-25 18:42:14 -0400503The following instances of :class:`EmailPolicy` provide defaults suitable for
504specific application domains. Note that in the future the behavior of these
Georg Brandl38e0e1e2012-05-27 09:31:10 +0200505instances (in particular the ``HTTP`` instance) may be adjusted to conform even
R David Murray0b6f6c82012-05-25 18:42:14 -0400506more closely to the RFCs relevant to their domains.
507
R David Murray29d1bc02016-09-07 21:15:59 -0400508
R David Murray0b6f6c82012-05-25 18:42:14 -0400509.. data:: default
510
511 An instance of ``EmailPolicy`` with all defaults unchanged. This policy
512 uses the standard Python ``\n`` line endings rather than the RFC-correct
513 ``\r\n``.
514
R David Murray29d1bc02016-09-07 21:15:59 -0400515
R David Murray0b6f6c82012-05-25 18:42:14 -0400516.. data:: SMTP
517
518 Suitable for serializing messages in conformance with the email RFCs.
519 Like ``default``, but with ``linesep`` set to ``\r\n``, which is RFC
520 compliant.
521
R David Murray29d1bc02016-09-07 21:15:59 -0400522
R David Murray1dbee942015-05-17 19:36:16 -0400523.. data:: SMTPUTF8
524
525 The same as ``SMTP`` except that :attr:`~EmailPolicy.utf8` is ``True``.
526 Useful for serializing messages to a message store without using encoded
527 words in the headers. Should only be used for SMTP trasmission if the
528 sender or recipient addresses have non-ASCII characters (the
529 :meth:`smtplib.SMTP.send_message` method handles this automatically).
530
R David Murray29d1bc02016-09-07 21:15:59 -0400531
R David Murray0b6f6c82012-05-25 18:42:14 -0400532.. data:: HTTP
533
534 Suitable for serializing headers with for use in HTTP traffic. Like
535 ``SMTP`` except that ``max_line_length`` is set to ``None`` (unlimited).
536
R David Murray29d1bc02016-09-07 21:15:59 -0400537
R David Murray0b6f6c82012-05-25 18:42:14 -0400538.. data:: strict
539
540 Convenience instance. The same as ``default`` except that
541 ``raise_on_defect`` is set to ``True``. This allows any policy to be made
542 strict by writing::
543
544 somepolicy + policy.strict
545
R David Murray29d1bc02016-09-07 21:15:59 -0400546
R David Murray0b6f6c82012-05-25 18:42:14 -0400547With all of these :class:`EmailPolicies <.EmailPolicy>`, the effective API of
548the email package is changed from the Python 3.2 API in the following ways:
549
550 * Setting a header on a :class:`~email.message.Message` results in that
R David Murray3da240f2013-10-16 22:48:40 -0400551 header being parsed and a header object created.
R David Murray0b6f6c82012-05-25 18:42:14 -0400552
553 * Fetching a header value from a :class:`~email.message.Message` results
R David Murray3da240f2013-10-16 22:48:40 -0400554 in that header being parsed and a header object created and
R David Murray0b6f6c82012-05-25 18:42:14 -0400555 returned.
556
R David Murray3da240f2013-10-16 22:48:40 -0400557 * Any header object, or any header that is refolded due to the
R David Murray0b6f6c82012-05-25 18:42:14 -0400558 policy settings, is folded using an algorithm that fully implements the
559 RFC folding algorithms, including knowing where encoded words are required
560 and allowed.
561
562From the application view, this means that any header obtained through the
R David Murray29d1bc02016-09-07 21:15:59 -0400563:class:`~email.message.EmailMessage` is a header object with extra
R David Murray0b6f6c82012-05-25 18:42:14 -0400564attributes, whose string value is the fully decoded unicode value of the
565header. Likewise, a header may be assigned a new value, or a new header
566created, using a unicode string, and the policy will take care of converting
567the unicode string into the correct RFC encoded form.
568
R David Murray3da240f2013-10-16 22:48:40 -0400569The header objects and their attributes are described in
R David Murrayea976682012-05-27 15:03:38 -0400570:mod:`~email.headerregistry`.
R David Murray29d1bc02016-09-07 21:15:59 -0400571
572
573
574.. class:: Compat32(**kw)
575
576 This concrete :class:`Policy` is the backward compatibility policy. It
577 replicates the behavior of the email package in Python 3.2. The
578 :mod:`~email.policy` module also defines an instance of this class,
579 :const:`compat32`, that is used as the default policy. Thus the default
580 behavior of the email package is to maintain compatibility with Python 3.2.
581
582 The following attributes have values that are different from the
583 :class:`Policy` default:
584
585
586 .. attribute:: mangle_from_
587
588 The default is ``True``.
589
590
591 The class provides the following concrete implementations of the
592 abstract methods of :class:`Policy`:
593
594
595 .. method:: header_source_parse(sourcelines)
596
597 The name is parsed as everything up to the '``:``' and returned
598 unmodified. The value is determined by stripping leading whitespace off
599 the remainder of the first line, joining all subsequent lines together,
600 and stripping any trailing carriage return or linefeed characters.
601
602
603 .. method:: header_store_parse(name, value)
604
605 The name and value are returned unmodified.
606
607
608 .. method:: header_fetch_parse(name, value)
609
610 If the value contains binary data, it is converted into a
611 :class:`~email.header.Header` object using the ``unknown-8bit`` charset.
612 Otherwise it is returned unmodified.
613
614
615 .. method:: fold(name, value)
616
617 Headers are folded using the :class:`~email.header.Header` folding
618 algorithm, which preserves existing line breaks in the value, and wraps
619 each resulting line to the ``max_line_length``. Non-ASCII binary data are
620 CTE encoded using the ``unknown-8bit`` charset.
621
622
623 .. method:: fold_binary(name, value)
624
625 Headers are folded using the :class:`~email.header.Header` folding
626 algorithm, which preserves existing line breaks in the value, and wraps
627 each resulting line to the ``max_line_length``. If ``cte_type`` is
628 ``7bit``, non-ascii binary data is CTE encoded using the ``unknown-8bit``
629 charset. Otherwise the original source header is used, with its existing
630 line breaks and any (RFC invalid) binary data it may contain.
631
632
633.. data:: compat32
634
635 An instance of :class:`Compat32`, providing backward compatibility with the
636 behavior of the email package in Python 3.2.