blob: 47f321227a4360832cab932de6634b113a48076c [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
21email. Some of these uses conform fairly closely to the main RFCs, some do
22not. And even when working with email, there are times when it is desirable to
23break strict compliance with the RFCs.
24
R David Murray6a45d3b2011-04-18 16:00:47 -040025Policy objects give the email package the flexibility to handle all these
26disparate use cases.
R David Murray3edd22a2011-04-18 13:59:37 -040027
28A :class:`Policy` object encapsulates a set of attributes and methods that
29control the behavior of various components of the email package during use.
30:class:`Policy` instances can be passed to various classes and methods in the
31email package to alter the default behavior. The settable values and their
R David Murrayc27e5222012-05-25 15:01:48 -040032defaults are described below.
R David Murray3edd22a2011-04-18 13:59:37 -040033
R David Murrayc27e5222012-05-25 15:01:48 -040034There is a default policy used by all classes in the email package. This
35policy is named :class:`Compat32`, with a corresponding pre-defined instance
36named :const:`compat32`. It provides for complete backward compatibility (in
37some cases, including bug compatibility) with the pre-Python3.3 version of the
38email package.
39
40The first part of this documentation covers the features of :class:`Policy`, an
41:term:`abstract base class` that defines the features that are common to all
42policy objects, including :const:`compat32`. This includes certain hook
43methods that are called internally by the email package, which a custom policy
44could override to obtain different behavior.
45
46When a :class:`~email.message.Message` object is created, it acquires a policy.
47By default this will be :const:`compat32`, but a different policy can be
48specified. If the ``Message`` is created by a :mod:`~email.parser`, a policy
49passed to the parser will be the policy used by the ``Message`` it creates. If
50the ``Message`` is created by the program, then the policy can be specified
51when it is created. When a ``Message`` is passed to a :mod:`~email.generator`,
52the generator uses the policy from the ``Message`` by default, but you can also
53pass a specific policy to the generator that will override the one stored on
54the ``Message`` object.
55
56:class:`Policy` instances are immutable, but they can be cloned, accepting the
57same keyword arguments as the class constructor and returning a new
58:class:`Policy` instance that is a copy of the original but with the specified
59attributes values changed.
R David Murray3edd22a2011-04-18 13:59:37 -040060
61As an example, the following code could be used to read an email message from a
R David Murrayfdfb0052013-07-29 15:49:58 -040062file on disk and pass it to the system ``sendmail`` program on a Unix system:
R David Murray3edd22a2011-04-18 13:59:37 -040063
R David Murrayfdfb0052013-07-29 15:49:58 -040064.. testsetup::
65
66 >>> from unittest import mock
67 >>> mocker = mock.patch('subprocess.Popen')
68 >>> m = mocker.start()
69 >>> proc = mock.MagicMock()
70 >>> m.return_value = proc
71 >>> proc.stdin.close.return_value = None
72 >>> mymsg = open('mymsg.txt', 'w')
73 >>> mymsg.write('To: abc@xyz.com\n\n')
74 17
75 >>> mymsg.flush()
76
77.. doctest::
78
79 >>> from email import message_from_binary_file
R David Murray3edd22a2011-04-18 13:59:37 -040080 >>> from email.generator import BytesGenerator
R David Murrayfdfb0052013-07-29 15:49:58 -040081 >>> from email import policy
R David Murray3edd22a2011-04-18 13:59:37 -040082 >>> from subprocess import Popen, PIPE
R David Murrayfdfb0052013-07-29 15:49:58 -040083 >>> with open('mymsg.txt', 'rb') as f:
84 ... msg = message_from_binary_file(f, policy=policy.default)
85 >>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)
R David Murrayc27e5222012-05-25 15:01:48 -040086 >>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n'))
R David Murray3edd22a2011-04-18 13:59:37 -040087 >>> g.flatten(msg)
88 >>> p.stdin.close()
89 >>> rc = p.wait()
90
R David Murray11bfd322013-07-30 14:42:40 -040091.. testsetup::
R David Murrayfdfb0052013-07-29 15:49:58 -040092
93 >>> mymsg.close()
94 >>> mocker.stop()
95 >>> import os
96 >>> os.remove('mymsg.txt')
97
R David Murrayc27e5222012-05-25 15:01:48 -040098Here we are telling :class:`~email.generator.BytesGenerator` to use the RFC
99correct line separator characters when creating the binary string to feed into
100``sendmail's`` ``stdin``, where the default policy would use ``\n`` line
101separators.
Éric Araujofe0472e2011-12-03 16:00:56 +0100102
R David Murray3edd22a2011-04-18 13:59:37 -0400103Some email package methods accept a *policy* keyword argument, allowing the
R David Murray6a45d3b2011-04-18 16:00:47 -0400104policy to be overridden for that method. For example, the following code uses
Barry Warsaw904c4812014-12-19 11:20:00 -0500105the :meth:`~email.message.Message.as_bytes` method of the *msg* object from
R David Murrayc27e5222012-05-25 15:01:48 -0400106the previous example and writes the message to a file using the native line
107separators for the platform on which it is running::
R David Murray3edd22a2011-04-18 13:59:37 -0400108
109 >>> import os
R David Murray3edd22a2011-04-18 13:59:37 -0400110 >>> with open('converted.txt', 'wb') as f:
R David Murraybb17d2b2013-08-09 16:15:28 -0400111 ... f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))
112 17
R David Murray3edd22a2011-04-18 13:59:37 -0400113
114Policy objects can also be combined using the addition operator, producing a
115policy object whose settings are a combination of the non-default values of the
116summed objects::
117
R David Murrayfdfb0052013-07-29 15:49:58 -0400118 >>> compat_SMTP = policy.compat32.clone(linesep='\r\n')
119 >>> compat_strict = policy.compat32.clone(raise_on_defect=True)
R David Murrayc27e5222012-05-25 15:01:48 -0400120 >>> compat_strict_SMTP = compat_SMTP + compat_strict
R David Murray3edd22a2011-04-18 13:59:37 -0400121
122This operation is not commutative; that is, the order in which the objects are
123added matters. To illustrate::
124
R David Murrayfdfb0052013-07-29 15:49:58 -0400125 >>> policy100 = policy.compat32.clone(max_line_length=100)
126 >>> policy80 = policy.compat32.clone(max_line_length=80)
127 >>> apolicy = policy100 + policy80
R David Murray3edd22a2011-04-18 13:59:37 -0400128 >>> apolicy.max_line_length
129 80
R David Murrayc27e5222012-05-25 15:01:48 -0400130 >>> apolicy = policy80 + policy100
R David Murray3edd22a2011-04-18 13:59:37 -0400131 >>> apolicy.max_line_length
132 100
133
134
135.. class:: Policy(**kw)
136
R David Murrayc27e5222012-05-25 15:01:48 -0400137 This is the :term:`abstract base class` for all policy classes. It provides
138 default implementations for a couple of trivial methods, as well as the
139 implementation of the immutability property, the :meth:`clone` method, and
140 the constructor semantics.
141
142 The constructor of a policy class can be passed various keyword arguments.
143 The arguments that may be specified are any non-method properties on this
144 class, plus any additional non-method properties on the concrete class. A
145 value specified in the constructor will override the default value for the
146 corresponding attribute.
147
148 This class defines the following properties, and thus values for the
149 following may be passed in the constructor of any policy class:
R David Murray3edd22a2011-04-18 13:59:37 -0400150
151 .. attribute:: max_line_length
152
153 The maximum length of any line in the serialized output, not counting the
154 end of line character(s). Default is 78, per :rfc:`5322`. A value of
155 ``0`` or :const:`None` indicates that no line wrapping should be
156 done at all.
157
158 .. attribute:: linesep
159
160 The string to be used to terminate lines in serialized output. The
R David Murray6a45d3b2011-04-18 16:00:47 -0400161 default is ``\n`` because that's the internal end-of-line discipline used
R David Murrayc27e5222012-05-25 15:01:48 -0400162 by Python, though ``\r\n`` is required by the RFCs.
R David Murray3edd22a2011-04-18 13:59:37 -0400163
R David Murrayc27e5222012-05-25 15:01:48 -0400164 .. attribute:: cte_type
R David Murray3edd22a2011-04-18 13:59:37 -0400165
R David Murrayc27e5222012-05-25 15:01:48 -0400166 Controls the type of Content Transfer Encodings that may be or are
167 required to be used. The possible values are:
168
Georg Brandl44ea77b2013-03-28 13:28:44 +0100169 .. tabularcolumns:: |l|L|
170
R David Murrayc27e5222012-05-25 15:01:48 -0400171 ======== ===============================================================
172 ``7bit`` all data must be "7 bit clean" (ASCII-only). This means that
173 where necessary data will be encoded using either
174 quoted-printable or base64 encoding.
175
176 ``8bit`` data is not constrained to be 7 bit clean. Data in headers is
177 still required to be ASCII-only and so will be encoded (see
178 'binary_fold' below for an exception), but body parts may use
179 the ``8bit`` CTE.
180 ======== ===============================================================
181
182 A ``cte_type`` value of ``8bit`` only works with ``BytesGenerator``, not
183 ``Generator``, because strings cannot contain binary data. If a
184 ``Generator`` is operating under a policy that specifies
185 ``cte_type=8bit``, it will act as if ``cte_type`` is ``7bit``.
R David Murray3edd22a2011-04-18 13:59:37 -0400186
187 .. attribute:: raise_on_defect
188
189 If :const:`True`, any defects encountered will be raised as errors. If
190 :const:`False` (the default), defects will be passed to the
191 :meth:`register_defect` method.
192
R David Murrayfdb23c22015-05-17 14:24:33 -0400193
194
195 .. attribute:: mangle_from\_
196
197 If :const:`True`, lines starting with *"From "* in the body are
198 escaped by putting a ``>`` in front of them. This parameter is used when
199 the message is being serialized by a generator.
200 Default: :const:`False`.
201
202 .. versionadded:: 3.5
203 The *mangle_from_* parameter.
204
R David Murrayc27e5222012-05-25 15:01:48 -0400205 The following :class:`Policy` method is intended to be called by code using
206 the email library to create policy instances with custom settings:
R David Murray6a45d3b2011-04-18 16:00:47 -0400207
R David Murrayc27e5222012-05-25 15:01:48 -0400208 .. method:: clone(**kw)
R David Murray3edd22a2011-04-18 13:59:37 -0400209
210 Return a new :class:`Policy` instance whose attributes have the same
211 values as the current instance, except where those attributes are
212 given new values by the keyword arguments.
213
R David Murrayc27e5222012-05-25 15:01:48 -0400214 The remaining :class:`Policy` methods are called by the email package code,
215 and are not intended to be called by an application using the email package.
216 A custom policy must implement all of these methods.
R David Murray3edd22a2011-04-18 13:59:37 -0400217
R David Murrayc27e5222012-05-25 15:01:48 -0400218 .. method:: handle_defect(obj, defect)
R David Murray3edd22a2011-04-18 13:59:37 -0400219
R David Murrayc27e5222012-05-25 15:01:48 -0400220 Handle a *defect* found on *obj*. When the email package calls this
221 method, *defect* will always be a subclass of
222 :class:`~email.errors.Defect`.
R David Murray3edd22a2011-04-18 13:59:37 -0400223
R David Murrayc27e5222012-05-25 15:01:48 -0400224 The default implementation checks the :attr:`raise_on_defect` flag. If
225 it is ``True``, *defect* is raised as an exception. If it is ``False``
226 (the default), *obj* and *defect* are passed to :meth:`register_defect`.
R David Murray3edd22a2011-04-18 13:59:37 -0400227
R David Murrayc27e5222012-05-25 15:01:48 -0400228 .. method:: register_defect(obj, defect)
R David Murray3edd22a2011-04-18 13:59:37 -0400229
R David Murrayc27e5222012-05-25 15:01:48 -0400230 Register a *defect* on *obj*. In the email package, *defect* will always
231 be a subclass of :class:`~email.errors.Defect`.
R David Murray3edd22a2011-04-18 13:59:37 -0400232
R David Murrayc27e5222012-05-25 15:01:48 -0400233 The default implementation calls the ``append`` method of the ``defects``
234 attribute of *obj*. When the email package calls :attr:`handle_defect`,
235 *obj* will normally have a ``defects`` attribute that has an ``append``
236 method. Custom object types used with the email package (for example,
237 custom ``Message`` objects) should also provide such an attribute,
238 otherwise defects in parsed messages will raise unexpected errors.
R David Murray3edd22a2011-04-18 13:59:37 -0400239
R David Murrayabfc3742012-05-29 09:14:44 -0400240 .. method:: header_max_count(name)
241
242 Return the maximum allowed number of headers named *name*.
243
244 Called when a header is added to a :class:`~email.message.Message`
245 object. If the returned value is not ``0`` or ``None``, and there are
246 already a number of headers with the name *name* equal to the value
247 returned, a :exc:`ValueError` is raised.
248
249 Because the default behavior of ``Message.__setitem__`` is to append the
250 value to the list of headers, it is easy to create duplicate headers
251 without realizing it. This method allows certain headers to be limited
252 in the number of instances of that header that may be added to a
253 ``Message`` programmatically. (The limit is not observed by the parser,
254 which will faithfully produce as many headers as exist in the message
255 being parsed.)
256
257 The default implementation returns ``None`` for all header names.
258
R David Murrayc27e5222012-05-25 15:01:48 -0400259 .. method:: header_source_parse(sourcelines)
R David Murray3edd22a2011-04-18 13:59:37 -0400260
R David Murrayc27e5222012-05-25 15:01:48 -0400261 The email package calls this method with a list of strings, each string
262 ending with the line separation characters found in the source being
263 parsed. The first line includes the field header name and separator.
264 All whitespace in the source is preserved. The method should return the
265 ``(name, value)`` tuple that is to be stored in the ``Message`` to
266 represent the parsed header.
R David Murray3edd22a2011-04-18 13:59:37 -0400267
R David Murrayc27e5222012-05-25 15:01:48 -0400268 If an implementation wishes to retain compatibility with the existing
269 email package policies, *name* should be the case preserved name (all
270 characters up to the '``:``' separator), while *value* should be the
271 unfolded value (all line separator characters removed, but whitespace
272 kept intact), stripped of leading whitespace.
R David Murray3edd22a2011-04-18 13:59:37 -0400273
R David Murrayc27e5222012-05-25 15:01:48 -0400274 *sourcelines* may contain surrogateescaped binary data.
275
276 There is no default implementation
277
278 .. method:: header_store_parse(name, value)
279
280 The email package calls this method with the name and value provided by
281 the application program when the application program is modifying a
282 ``Message`` programmatically (as opposed to a ``Message`` created by a
283 parser). The method should return the ``(name, value)`` tuple that is to
284 be stored in the ``Message`` to represent the header.
285
286 If an implementation wishes to retain compatibility with the existing
287 email package policies, the *name* and *value* should be strings or
288 string subclasses that do not change the content of the passed in
289 arguments.
290
291 There is no default implementation
292
293 .. method:: header_fetch_parse(name, value)
294
295 The email package calls this method with the *name* and *value* currently
296 stored in the ``Message`` when that header is requested by the
297 application program, and whatever the method returns is what is passed
298 back to the application as the value of the header being retrieved.
299 Note that there may be more than one header with the same name stored in
300 the ``Message``; the method is passed the specific name and value of the
301 header destined to be returned to the application.
302
303 *value* may contain surrogateescaped binary data. There should be no
304 surrogateescaped binary data in the value returned by the method.
305
306 There is no default implementation
307
308 .. method:: fold(name, value)
309
310 The email package calls this method with the *name* and *value* currently
311 stored in the ``Message`` for a given header. The method should return a
312 string that represents that header "folded" correctly (according to the
313 policy settings) by composing the *name* with the *value* and inserting
314 :attr:`linesep` characters at the appropriate places. See :rfc:`5322`
315 for a discussion of the rules for folding email headers.
316
317 *value* may contain surrogateescaped binary data. There should be no
318 surrogateescaped binary data in the string returned by the method.
319
320 .. method:: fold_binary(name, value)
321
322 The same as :meth:`fold`, except that the returned value should be a
323 bytes object rather than a string.
324
325 *value* may contain surrogateescaped binary data. These could be
326 converted back into binary data in the returned bytes object.
327
328
329.. class:: Compat32(**kw)
330
331 This concrete :class:`Policy` is the backward compatibility policy. It
332 replicates the behavior of the email package in Python 3.2. The
Serhiy Storchakae0f0cf42013-08-19 09:59:18 +0300333 :mod:`~email.policy` module also defines an instance of this class,
R David Murrayc27e5222012-05-25 15:01:48 -0400334 :const:`compat32`, that is used as the default policy. Thus the default
335 behavior of the email package is to maintain compatibility with Python 3.2.
336
R David Murrayfdb23c22015-05-17 14:24:33 -0400337 The following attributes have values that are different from the
338 :class:`Policy` default:
339
340 .. attribute:: mangle_from_
341
342 The default is ``True``.
343
R David Murrayc27e5222012-05-25 15:01:48 -0400344 The class provides the following concrete implementations of the
345 abstract methods of :class:`Policy`:
346
347 .. method:: header_source_parse(sourcelines)
348
349 The name is parsed as everything up to the '``:``' and returned
350 unmodified. The value is determined by stripping leading whitespace off
351 the remainder of the first line, joining all subsequent lines together,
352 and stripping any trailing carriage return or linefeed characters.
353
354 .. method:: header_store_parse(name, value)
355
356 The name and value are returned unmodified.
357
358 .. method:: header_fetch_parse(name, value)
359
360 If the value contains binary data, it is converted into a
361 :class:`~email.header.Header` object using the ``unknown-8bit`` charset.
362 Otherwise it is returned unmodified.
363
364 .. method:: fold(name, value)
365
366 Headers are folded using the :class:`~email.header.Header` folding
367 algorithm, which preserves existing line breaks in the value, and wraps
368 each resulting line to the ``max_line_length``. Non-ASCII binary data are
369 CTE encoded using the ``unknown-8bit`` charset.
370
371 .. method:: fold_binary(name, value)
372
373 Headers are folded using the :class:`~email.header.Header` folding
374 algorithm, which preserves existing line breaks in the value, and wraps
375 each resulting line to the ``max_line_length``. If ``cte_type`` is
376 ``7bit``, non-ascii binary data is CTE encoded using the ``unknown-8bit``
377 charset. Otherwise the original source header is used, with its existing
Terry Jan Reedy0f847642013-03-11 18:34:00 -0400378 line breaks and any (RFC invalid) binary data it may contain.
R David Murray0b6f6c82012-05-25 18:42:14 -0400379
380
R David Murrayfdb23c22015-05-17 14:24:33 -0400381An instance of :class:`Compat32` is provided as a module constant:
382
383.. data:: compat32
384
385 An instance of :class:`Compat32`, providing backward compatibility with the
386 behavior of the email package in Python 3.2.
387
388
R David Murray0b6f6c82012-05-25 18:42:14 -0400389.. note::
390
R David Murrayea976682012-05-27 15:03:38 -0400391 The documentation below describes new policies that are included in the
392 standard library on a :term:`provisional basis <provisional package>`.
393 Backwards incompatible changes (up to and including removal of the feature)
394 may occur if deemed necessary by the core developers.
R David Murray0b6f6c82012-05-25 18:42:14 -0400395
396
397.. class:: EmailPolicy(**kw)
398
399 This concrete :class:`Policy` provides behavior that is intended to be fully
400 compliant with the current email RFCs. These include (but are not limited
401 to) :rfc:`5322`, :rfc:`2047`, and the current MIME RFCs.
402
403 This policy adds new header parsing and folding algorithms. Instead of
R David Murray3da240f2013-10-16 22:48:40 -0400404 simple strings, headers are ``str`` subclasses with attributes that depend
R David Murray0b6f6c82012-05-25 18:42:14 -0400405 on the type of the field. The parsing and folding algorithm fully implement
406 :rfc:`2047` and :rfc:`5322`.
407
408 In addition to the settable attributes listed above that apply to all
409 policies, this policy adds the following additional attributes:
410
R David Murray224ef3e2015-05-17 11:29:21 -0400411 .. attribute:: utf8
412
413 If ``False``, follow :rfc:`5322`, supporting non-ASCII characters in
414 headers by encoding them as "encoded words". If ``True``, follow
415 :rfc:`6532` and use ``utf-8`` encoding for headers. Messages
416 formatted in this way may be passed to SMTP servers that support
417 the ``SMTPUTF8`` extension (:rfc:`6531`).
418
R David Murray0b6f6c82012-05-25 18:42:14 -0400419 .. attribute:: refold_source
420
421 If the value for a header in the ``Message`` object originated from a
422 :mod:`~email.parser` (as opposed to being set by a program), this
423 attribute indicates whether or not a generator should refold that value
424 when transforming the message back into stream form. The possible values
425 are:
426
427 ======== ===============================================================
428 ``none`` all source values use original folding
429
430 ``long`` source values that have any line that is longer than
431 ``max_line_length`` will be refolded
432
433 ``all`` all values are refolded.
434 ======== ===============================================================
435
436 The default is ``long``.
437
438 .. attribute:: header_factory
439
440 A callable that takes two arguments, ``name`` and ``value``, where
441 ``name`` is a header field name and ``value`` is an unfolded header field
R David Murrayea976682012-05-27 15:03:38 -0400442 value, and returns a string subclass that represents that header. A
443 default ``header_factory`` (see :mod:`~email.headerregistry`) is provided
444 that understands some of the :RFC:`5322` header field types. (Currently
445 address fields and date fields have special treatment, while all other
446 fields are treated as unstructured. This list will be completed before
447 the extension is marked stable.)
R David Murray0b6f6c82012-05-25 18:42:14 -0400448
R David Murray3da240f2013-10-16 22:48:40 -0400449 .. attribute:: content_manager
450
451 An object with at least two methods: get_content and set_content. When
452 the :meth:`~email.message.Message.get_content` or
453 :meth:`~email.message.Message.set_content` method of a
454 :class:`~email.message.Message` object is called, it calls the
455 corresponding method of this object, passing it the message object as its
456 first argument, and any arguments or keywords that were passed to it as
457 additional arguments. By default ``content_manager`` is set to
458 :data:`~email.contentmanager.raw_data_manager`.
459
Larry Hastings3732ed22014-03-15 21:13:56 -0700460 .. versionadded:: 3.4
R David Murray3da240f2013-10-16 22:48:40 -0400461
462
R David Murray0b6f6c82012-05-25 18:42:14 -0400463 The class provides the following concrete implementations of the abstract
464 methods of :class:`Policy`:
465
R David Murrayabfc3742012-05-29 09:14:44 -0400466 .. method:: header_max_count(name)
467
468 Returns the value of the
469 :attr:`~email.headerregistry.BaseHeader.max_count` attribute of the
470 specialized class used to represent the header with the given name.
471
R David Murray0b6f6c82012-05-25 18:42:14 -0400472 .. method:: header_source_parse(sourcelines)
473
474 The implementation of this method is the same as that for the
475 :class:`Compat32` policy.
476
477 .. method:: header_store_parse(name, value)
478
479 The name is returned unchanged. If the input value has a ``name``
480 attribute and it matches *name* ignoring case, the value is returned
481 unchanged. Otherwise the *name* and *value* are passed to
R David Murray3da240f2013-10-16 22:48:40 -0400482 ``header_factory``, and the resulting header object is returned as
R David Murray0b6f6c82012-05-25 18:42:14 -0400483 the value. In this case a ``ValueError`` is raised if the input value
484 contains CR or LF characters.
485
486 .. method:: header_fetch_parse(name, value)
487
488 If the value has a ``name`` attribute, it is returned to unmodified.
489 Otherwise the *name*, and the *value* with any CR or LF characters
R David Murray3da240f2013-10-16 22:48:40 -0400490 removed, are passed to the ``header_factory``, and the resulting
R David Murray0b6f6c82012-05-25 18:42:14 -0400491 header object is returned. Any surrogateescaped bytes get turned into
492 the unicode unknown-character glyph.
493
494 .. method:: fold(name, value)
495
496 Header folding is controlled by the :attr:`refold_source` policy setting.
497 A value is considered to be a 'source value' if and only if it does not
498 have a ``name`` attribute (having a ``name`` attribute means it is a
499 header object of some sort). If a source value needs to be refolded
R David Murray3da240f2013-10-16 22:48:40 -0400500 according to the policy, it is converted into a header object by
R David Murray0b6f6c82012-05-25 18:42:14 -0400501 passing the *name* and the *value* with any CR and LF characters removed
R David Murray3da240f2013-10-16 22:48:40 -0400502 to the ``header_factory``. Folding of a header object is done by
R David Murray0b6f6c82012-05-25 18:42:14 -0400503 calling its ``fold`` method with the current policy.
504
505 Source values are split into lines using :meth:`~str.splitlines`. If
506 the value is not to be refolded, the lines are rejoined using the
507 ``linesep`` from the policy and returned. The exception is lines
508 containing non-ascii binary data. In that case the value is refolded
509 regardless of the ``refold_source`` setting, which causes the binary data
510 to be CTE encoded using the ``unknown-8bit`` charset.
511
512 .. method:: fold_binary(name, value)
513
Serhiy Storchakae0f0cf42013-08-19 09:59:18 +0300514 The same as :meth:`fold` if :attr:`~Policy.cte_type` is ``7bit``, except
515 that the returned value is bytes.
R David Murray0b6f6c82012-05-25 18:42:14 -0400516
Serhiy Storchakae0f0cf42013-08-19 09:59:18 +0300517 If :attr:`~Policy.cte_type` is ``8bit``, non-ASCII binary data is
518 converted back
R David Murray0b6f6c82012-05-25 18:42:14 -0400519 into bytes. Headers with binary data are not refolded, regardless of the
520 ``refold_header`` setting, since there is no way to know whether the
521 binary data consists of single byte characters or multibyte characters.
522
523The following instances of :class:`EmailPolicy` provide defaults suitable for
524specific application domains. Note that in the future the behavior of these
Georg Brandl38e0e1e2012-05-27 09:31:10 +0200525instances (in particular the ``HTTP`` instance) may be adjusted to conform even
R David Murray0b6f6c82012-05-25 18:42:14 -0400526more closely to the RFCs relevant to their domains.
527
528.. data:: default
529
530 An instance of ``EmailPolicy`` with all defaults unchanged. This policy
531 uses the standard Python ``\n`` line endings rather than the RFC-correct
532 ``\r\n``.
533
534.. data:: SMTP
535
536 Suitable for serializing messages in conformance with the email RFCs.
537 Like ``default``, but with ``linesep`` set to ``\r\n``, which is RFC
538 compliant.
539
R David Murray1dbee942015-05-17 19:36:16 -0400540.. data:: SMTPUTF8
541
542 The same as ``SMTP`` except that :attr:`~EmailPolicy.utf8` is ``True``.
543 Useful for serializing messages to a message store without using encoded
544 words in the headers. Should only be used for SMTP trasmission if the
545 sender or recipient addresses have non-ASCII characters (the
546 :meth:`smtplib.SMTP.send_message` method handles this automatically).
547
R David Murray0b6f6c82012-05-25 18:42:14 -0400548.. data:: HTTP
549
550 Suitable for serializing headers with for use in HTTP traffic. Like
551 ``SMTP`` except that ``max_line_length`` is set to ``None`` (unlimited).
552
553.. data:: strict
554
555 Convenience instance. The same as ``default`` except that
556 ``raise_on_defect`` is set to ``True``. This allows any policy to be made
557 strict by writing::
558
559 somepolicy + policy.strict
560
561With all of these :class:`EmailPolicies <.EmailPolicy>`, the effective API of
562the email package is changed from the Python 3.2 API in the following ways:
563
564 * Setting a header on a :class:`~email.message.Message` results in that
R David Murray3da240f2013-10-16 22:48:40 -0400565 header being parsed and a header object created.
R David Murray0b6f6c82012-05-25 18:42:14 -0400566
567 * Fetching a header value from a :class:`~email.message.Message` results
R David Murray3da240f2013-10-16 22:48:40 -0400568 in that header being parsed and a header object created and
R David Murray0b6f6c82012-05-25 18:42:14 -0400569 returned.
570
R David Murray3da240f2013-10-16 22:48:40 -0400571 * Any header object, or any header that is refolded due to the
R David Murray0b6f6c82012-05-25 18:42:14 -0400572 policy settings, is folded using an algorithm that fully implements the
573 RFC folding algorithms, including knowing where encoded words are required
574 and allowed.
575
576From the application view, this means that any header obtained through the
R David Murray3da240f2013-10-16 22:48:40 -0400577:class:`~email.message.Message` is a header object with extra
R David Murray0b6f6c82012-05-25 18:42:14 -0400578attributes, whose string value is the fully decoded unicode value of the
579header. Likewise, a header may be assigned a new value, or a new header
580created, using a unicode string, and the policy will take care of converting
581the unicode string into the correct RFC encoded form.
582
R David Murray3da240f2013-10-16 22:48:40 -0400583The header objects and their attributes are described in
R David Murrayea976682012-05-27 15:03:38 -0400584:mod:`~email.headerregistry`.