| 1 |
:mod:`!email.utils`: Miscellaneous utilities |
| 2 |
-------------------------------------------- |
| 3 |
|
| 4 |
.. module:: email.utils |
| 5 |
:synopsis: Miscellaneous email package utilities. |
| 6 |
|
| 7 |
**Source code:** :source:`Lib/email/utils.py` |
| 8 |
|
| 9 |
-------------- |
| 10 |
|
| 11 |
There are a couple of useful utilities provided in the :mod:`!email.utils` |
| 12 |
module: |
| 13 |
|
| 14 |
.. function:: localtime(dt=None) |
| 15 |
|
| 16 |
Return local time as an aware datetime object. If called without |
| 17 |
arguments, return current time. Otherwise *dt* argument should be a |
| 18 |
:class:`~datetime.datetime` instance, and it is converted to the local time |
| 19 |
zone according to the system time zone database. If *dt* is naive (that |
| 20 |
is, ``dt.tzinfo`` is ``None``), it is assumed to be in local time. |
| 21 |
|
| 22 |
.. versionadded:: 3.3 |
| 23 |
|
| 24 |
.. deprecated-removed:: 3.12 3.14 |
| 25 |
The *isdst* parameter. |
| 26 |
|
| 27 |
.. function:: make_msgid(idstring=None, domain=None) |
| 28 |
|
| 29 |
Returns a string suitable for an :rfc:`2822`\ -compliant |
| 30 |
:mailheader:`Message-ID` header. Optional *idstring* if given, is a string |
| 31 |
used to strengthen the uniqueness of the message id. Optional *domain* if |
| 32 |
given provides the portion of the msgid after the '@'. The default is the |
| 33 |
local hostname. It is not normally necessary to override this default, but |
| 34 |
may be useful certain cases, such as a constructing distributed system that |
| 35 |
uses a consistent domain name across multiple hosts. |
| 36 |
|
| 37 |
.. versionchanged:: 3.2 |
| 38 |
Added the *domain* keyword. |
| 39 |
|
| 40 |
|
| 41 |
The remaining functions are part of the legacy (``Compat32``) email API. There |
| 42 |
is no need to directly use these with the new API, since the parsing and |
| 43 |
formatting they provide is done automatically by the header parsing machinery |
| 44 |
of the new API. |
| 45 |
|
| 46 |
|
| 47 |
.. function:: quote(str) |
| 48 |
|
| 49 |
Return a new string with backslashes in *str* replaced by two backslashes, and |
| 50 |
double quotes replaced by backslash-double quote. |
| 51 |
|
| 52 |
|
| 53 |
.. function:: unquote(str) |
| 54 |
|
| 55 |
Return a new string which is an *unquoted* version of *str*. If *str* ends and |
| 56 |
begins with double quotes, they are stripped off. Likewise if *str* ends and |
| 57 |
begins with angle brackets, they are stripped off. |
| 58 |
|
| 59 |
|
| 60 |
.. function:: parseaddr(address, *, strict=True) |
| 61 |
|
| 62 |
Parse address -- which should be the value of some address-containing field such |
| 63 |
as :mailheader:`To` or :mailheader:`Cc` -- into its constituent *realname* and |
| 64 |
*email address* parts. Returns a tuple of that information, unless the parse |
| 65 |
fails, in which case a 2-tuple of ``('', '')`` is returned. |
| 66 |
|
| 67 |
If *strict* is true, use a strict parser which rejects malformed inputs. |
| 68 |
|
| 69 |
.. versionchanged:: 3.13 |
| 70 |
Add *strict* optional parameter and reject malformed inputs by default. |
| 71 |
|
| 72 |
|
| 73 |
.. function:: formataddr(pair, charset='utf-8') |
| 74 |
|
| 75 |
The inverse of :meth:`parseaddr`, this takes a 2-tuple of the form ``(realname, |
| 76 |
email_address)`` and returns the string value suitable for a :mailheader:`To` or |
| 77 |
:mailheader:`Cc` header. If the first element of *pair* is false, then the |
| 78 |
second element is returned unmodified. |
| 79 |
|
| 80 |
Optional *charset* is the character set that will be used in the :rfc:`2047` |
| 81 |
encoding of the ``realname`` if the ``realname`` contains non-ASCII |
| 82 |
characters. Can be an instance of :class:`str` or a |
| 83 |
:class:`~email.charset.Charset`. Defaults to ``utf-8``. |
| 84 |
|
| 85 |
.. versionchanged:: 3.3 |
| 86 |
Added the *charset* option. |
| 87 |
|
| 88 |
|
| 89 |
.. function:: getaddresses(fieldvalues, *, strict=True) |
| 90 |
|
| 91 |
This method returns a list of 2-tuples of the form returned by ``parseaddr()``. |
| 92 |
*fieldvalues* is a sequence of header field values as might be returned by |
| 93 |
:meth:`Message.get_all <email.message.Message.get_all>`. |
| 94 |
|
| 95 |
If *strict* is true, use a strict parser which rejects malformed inputs. |
| 96 |
|
| 97 |
Here's a simple example that gets all the recipients of a message:: |
| 98 |
|
| 99 |
from email.utils import getaddresses |
| 100 |
|
| 101 |
tos = msg.get_all('to', []) |
| 102 |
ccs = msg.get_all('cc', []) |
| 103 |
resent_tos = msg.get_all('resent-to', []) |
| 104 |
resent_ccs = msg.get_all('resent-cc', []) |
| 105 |
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs) |
| 106 |
|
| 107 |
.. versionchanged:: 3.13 |
| 108 |
Add *strict* optional parameter and reject malformed inputs by default. |
| 109 |
|
| 110 |
|
| 111 |
.. function:: parsedate(date) |
| 112 |
|
| 113 |
Attempts to parse a date according to the rules in :rfc:`2822`. however, some |
| 114 |
mailers don't follow that format as specified, so :func:`parsedate` tries to |
| 115 |
guess correctly in such cases. *date* is a string containing an :rfc:`2822` |
| 116 |
date, such as ``"Mon, 20 Nov 1995 19:12:08 -0500"``. If it succeeds in parsing |
| 117 |
the date, :func:`parsedate` returns a 9-tuple that can be passed directly to |
| 118 |
:func:`time.mktime`; otherwise ``None`` will be returned. Note that indexes 6, |
| 119 |
7, and 8 of the result tuple are not usable. |
| 120 |
|
| 121 |
|
| 122 |
.. function:: parsedate_tz(date) |
| 123 |
|
| 124 |
Performs the same function as :func:`parsedate`, but returns either ``None`` or |
| 125 |
a 10-tuple; the first 9 elements make up a tuple that can be passed directly to |
| 126 |
:func:`time.mktime`, and the tenth is the offset of the date's timezone from UTC |
| 127 |
(which is the official term for Greenwich Mean Time) [#]_. If the input string |
| 128 |
has no timezone, the last element of the tuple returned is ``0``, which represents |
| 129 |
UTC. Note that indexes 6, 7, and 8 of the result tuple are not usable. |
| 130 |
|
| 131 |
|
| 132 |
.. function:: parsedate_to_datetime(date) |
| 133 |
|
| 134 |
The inverse of :func:`format_datetime`. Performs the same function as |
| 135 |
:func:`parsedate`, but on success returns a :mod:`~datetime.datetime`; |
| 136 |
otherwise ``ValueError`` is raised if *date* contains an invalid value such |
| 137 |
as an hour greater than 23 or a timezone offset not between -24 and 24 hours. |
| 138 |
If the input date has a timezone of ``-0000``, the ``datetime`` will be a naive |
| 139 |
``datetime``, and if the date is conforming to the RFCs it will represent a |
| 140 |
time in UTC but with no indication of the actual source timezone of the |
| 141 |
message the date comes from. If the input date has any other valid timezone |
| 142 |
offset, the ``datetime`` will be an aware ``datetime`` with the |
| 143 |
corresponding a :class:`~datetime.timezone` :class:`~datetime.tzinfo`. |
| 144 |
|
| 145 |
.. versionadded:: 3.3 |
| 146 |
|
| 147 |
|
| 148 |
.. function:: mktime_tz(tuple) |
| 149 |
|
| 150 |
Turn a 10-tuple as returned by :func:`parsedate_tz` into a UTC |
| 151 |
timestamp (seconds since the Epoch). If the timezone item in the |
| 152 |
tuple is ``None``, assume local time. |
| 153 |
|
| 154 |
|
| 155 |
.. function:: formatdate(timeval=None, localtime=False, usegmt=False) |
| 156 |
|
| 157 |
Returns a date string as per :rfc:`2822`, e.g.:: |
| 158 |
|
| 159 |
Fri, 09 Nov 2001 01:08:47 -0000 |
| 160 |
|
| 161 |
Optional *timeval* if given is a floating-point time value as accepted by |
| 162 |
:func:`time.gmtime` and :func:`time.localtime`, otherwise the current time is |
| 163 |
used. |
| 164 |
|
| 165 |
Optional *localtime* is a flag that when ``True``, interprets *timeval*, and |
| 166 |
returns a date relative to the local timezone instead of UTC, properly taking |
| 167 |
daylight savings time into account. The default is ``False`` meaning UTC is |
| 168 |
used. |
| 169 |
|
| 170 |
Optional *usegmt* is a flag that when ``True``, outputs a date string with the |
| 171 |
timezone as an ascii string ``GMT``, rather than a numeric ``-0000``. This is |
| 172 |
needed for some protocols (such as HTTP). This only applies when *localtime* is |
| 173 |
``False``. The default is ``False``. |
| 174 |
|
| 175 |
|
| 176 |
.. function:: format_datetime(dt, usegmt=False) |
| 177 |
|
| 178 |
Like ``formatdate``, but the input is a :mod:`datetime` instance. If it is |
| 179 |
a naive datetime, it is assumed to be "UTC with no information about the |
| 180 |
source timezone", and the conventional ``-0000`` is used for the timezone. |
| 181 |
If it is an aware ``datetime``, then the numeric timezone offset is used. |
| 182 |
If it is an aware timezone with offset zero, then *usegmt* may be set to |
| 183 |
``True``, in which case the string ``GMT`` is used instead of the numeric |
| 184 |
timezone offset. This provides a way to generate standards conformant HTTP |
| 185 |
date headers. |
| 186 |
|
| 187 |
.. versionadded:: 3.3 |
| 188 |
|
| 189 |
|
| 190 |
.. function:: decode_rfc2231(s) |
| 191 |
|
| 192 |
Decode the string *s* according to :rfc:`2231`. |
| 193 |
|
| 194 |
|
| 195 |
.. function:: encode_rfc2231(s, charset=None, language=None) |
| 196 |
|
| 197 |
Encode the string *s* according to :rfc:`2231`. Optional *charset* and |
| 198 |
*language*, if given is the character set name and language name to use. If |
| 199 |
neither is given, *s* is returned as-is. If *charset* is given but *language* |
| 200 |
is not, the string is encoded using the empty string for *language*. |
| 201 |
|
| 202 |
|
| 203 |
.. function:: collapse_rfc2231_value(value, errors='replace', fallback_charset='us-ascii') |
| 204 |
|
| 205 |
When a header parameter is encoded in :rfc:`2231` format, |
| 206 |
:meth:`Message.get_param <email.message.Message.get_param>` may return a |
| 207 |
3-tuple containing the character set, |
| 208 |
language, and value. :func:`collapse_rfc2231_value` turns this into a unicode |
| 209 |
string. Optional *errors* is passed to the *errors* argument of :class:`str`'s |
| 210 |
:func:`~str.encode` method; it defaults to ``'replace'``. Optional |
| 211 |
*fallback_charset* specifies the character set to use if the one in the |
| 212 |
:rfc:`2231` header is not known by Python; it defaults to ``'us-ascii'``. |
| 213 |
|
| 214 |
For convenience, if the *value* passed to :func:`collapse_rfc2231_value` is not |
| 215 |
a tuple, it should be a string and it is returned unquoted. |
| 216 |
|
| 217 |
|
| 218 |
.. function:: decode_params(params) |
| 219 |
|
| 220 |
Decode parameters list according to :rfc:`2231`. *params* is a sequence of |
| 221 |
2-tuples containing elements of the form ``(content-type, string-value)``. |
| 222 |
|
| 223 |
|
| 224 |
.. rubric:: Footnotes |
| 225 |
|
| 226 |
.. [#] Note that the sign of the timezone offset is the opposite of the sign of the |
| 227 |
``time.timezone`` variable for the same timezone; the latter variable follows |
| 228 |
the POSIX standard while this module follows :rfc:`2822`. |