blob: 157f692267902469d27b369683be7e1dc0e1e713 [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
R David Murray6a45d3b2011-04-18 16:00:47 -04007.. versionadded: 3.3
8
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:
R David Murray6a45d3b2011-04-18 16:00:47 -040051 ... 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
58Some email package methods accept a *policy* keyword argument, allowing the
R David Murray6a45d3b2011-04-18 16:00:47 -040059policy to be overridden for that method. For example, the following code uses
60the :meth:`email.message.Message.as_string` method of the *msg* object from the
R David Murray3edd22a2011-04-18 13:59:37 -040061previous example and re-write it to a file using the native line separators for
62the platform on which it is running::
63
64 >>> import os
65 >>> mypolicy = email.policy.Policy(linesep=os.linesep)
66 >>> with open('converted.txt', 'wb') as f:
67 ... f.write(msg.as_string(policy=mypolicy))
68
69Policy instances are immutable, but they can be cloned, accepting the same
70keyword arguments as the class constructor and returning a new :class:`Policy`
71instance that is a copy of the original but with the specified attributes
72values changed. For example, the following creates an SMTP policy that will
73raise any defects detected as errors::
74
75 >>> strict_SMTP = email.policy.SMTP.clone(raise_on_defect=True)
76
77Policy objects can also be combined using the addition operator, producing a
78policy object whose settings are a combination of the non-default values of the
79summed objects::
80
81 >>> strict_SMTP = email.policy.SMTP + email.policy.strict
82
83This operation is not commutative; that is, the order in which the objects are
84added matters. To illustrate::
85
86 >>> Policy = email.policy.Policy
87 >>> apolicy = Policy(max_line_length=100) + Policy(max_line_length=80)
88 >>> apolicy.max_line_length
89 80
90 >>> apolicy = Policy(max_line_length=80) + Policy(max_line_length=100)
91 >>> apolicy.max_line_length
92 100
93
94
95.. class:: Policy(**kw)
96
97 The valid constructor keyword arguments are any of the attributes listed
98 below.
99
100 .. attribute:: max_line_length
101
102 The maximum length of any line in the serialized output, not counting the
103 end of line character(s). Default is 78, per :rfc:`5322`. A value of
104 ``0`` or :const:`None` indicates that no line wrapping should be
105 done at all.
106
107 .. attribute:: linesep
108
109 The string to be used to terminate lines in serialized output. The
R David Murray6a45d3b2011-04-18 16:00:47 -0400110 default is ``\n`` because that's the internal end-of-line discipline used
111 by Python, though ``\r\n`` is required by the RFCs. See `Policy
R David Murray3edd22a2011-04-18 13:59:37 -0400112 Instances`_ for policies that use an RFC conformant linesep. Setting it
113 to :attr:`os.linesep` may also be useful.
114
115 .. attribute:: must_be_7bit
116
R David Murray6a45d3b2011-04-18 16:00:47 -0400117 If ``True``, data output by a bytes generator is limited to ASCII
R David Murray3edd22a2011-04-18 13:59:37 -0400118 characters. If :const:`False` (the default), then bytes with the high
119 bit set are preserved and/or allowed in certain contexts (for example,
120 where possible a content transfer encoding of ``8bit`` will be used).
R David Murray6a45d3b2011-04-18 16:00:47 -0400121 String generators act as if ``must_be_7bit`` is ``True`` regardless of
122 the policy in effect, since a string cannot represent non-ASCII bytes.
R David Murray3edd22a2011-04-18 13:59:37 -0400123
124 .. attribute:: raise_on_defect
125
126 If :const:`True`, any defects encountered will be raised as errors. If
127 :const:`False` (the default), defects will be passed to the
128 :meth:`register_defect` method.
129
R David Murray6a45d3b2011-04-18 16:00:47 -0400130 :mod:`Policy` object also have the following methods:
131
R David Murray3edd22a2011-04-18 13:59:37 -0400132 .. method:: handle_defect(obj, defect)
133
134 *obj* is the object on which to register the defect. *defect* should be
135 an instance of a subclass of :class:`~email.errors.Defect`.
136 If :attr:`raise_on_defect`
137 is ``True`` the defect is raised as an exception. Otherwise *obj* and
138 *defect* are passed to :meth:`register_defect`. This method is intended
139 to be called by parsers when they encounter defects, and will not be
140 called by code that uses the email library unless that code is
141 implementing an alternate parser.
142
143 .. method:: register_defect(obj, defect)
144
145 *obj* is the object on which to register the defect. *defect* should be
146 a subclass of :class:`~email.errors.Defect`. This method is part of the
147 public API so that custom ``Policy`` subclasses can implement alternate
148 handling of defects. The default implementation calls the ``append``
149 method of the ``defects`` attribute of *obj*.
150
R David Murray6a45d3b2011-04-18 16:00:47 -0400151 .. method:: clone(obj, *kw)
R David Murray3edd22a2011-04-18 13:59:37 -0400152
153 Return a new :class:`Policy` instance whose attributes have the same
154 values as the current instance, except where those attributes are
155 given new values by the keyword arguments.
156
157
158Policy Instances
R David Murray6a45d3b2011-04-18 16:00:47 -0400159^^^^^^^^^^^^^^^^
R David Murray3edd22a2011-04-18 13:59:37 -0400160
161The following instances of :class:`Policy` provide defaults suitable for
162specific common application domains.
163
164.. data:: default
165
R David Murray6a45d3b2011-04-18 16:00:47 -0400166 An instance of :class:`Policy` with all defaults unchanged.
R David Murray3edd22a2011-04-18 13:59:37 -0400167
168.. data:: SMTP
169
R David Murray6a45d3b2011-04-18 16:00:47 -0400170 Output serialized from a message will conform to the email and SMTP
171 RFCs. The only changed attribute is :attr:`linesep`, which is set to
172 ``\r\n``.
R David Murray3edd22a2011-04-18 13:59:37 -0400173
174.. data:: HTTP
175
R David Murray6a45d3b2011-04-18 16:00:47 -0400176 Suitable for use when serializing headers for use in HTTP traffic.
177 :attr:`linesep` is set to ``\r\n``, and :attr:`max_line_length` is set to
178 :const:`None` (unlimited).
R David Murray3edd22a2011-04-18 13:59:37 -0400179
180.. data:: strict
181
R David Murray6a45d3b2011-04-18 16:00:47 -0400182 :attr:`raise_on_defect` is set to :const:`True`.