◐ Shell
reader mode source ↗
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
File filter
Conversations
Jump to
Diff view
Apply and reload
Show whitespace
Diff view
Apply and reload
19 changes: 15 additions & 4 deletions Doc/library/email.utils.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,18 @@ of the new API.
begins with angle brackets, they are stripped off.


.. function:: parseaddr(address)

Parse address -- which should be the value of some address-containing field such
as :mailheader:`To` or :mailheader:`Cc` -- into its constituent *realname* and
*email address* parts. Returns a tuple of that information, unless the parse
fails, in which case a 2-tuple of ``('', '')`` is returned.


.. function:: formataddr(pair, charset='utf-8')

Expand All @@ -84,12 +89,15 @@ of the new API.
Added the *charset* option.


.. function:: getaddresses(fieldvalues)

This method returns a list of 2-tuples of the form returned by ``parseaddr()``.
*fieldvalues* is a sequence of header field values as might be returned by
:meth:`Message.get_all <email.message.Message.get_all>`. Here's a simple
example that gets all the recipients of a message::

from email.utils import getaddresses

Expand All @@ -99,6 +107,9 @@ of the new API.
resent_ccs = msg.get_all('resent-cc', [])
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)


.. function:: parsedate(date)

Expand Down
10 changes: 10 additions & 0 deletions Doc/whatsnew/3.11.rst
Original file line number Diff line number Diff line change
@@ -2776,3 +2776,13 @@ email
If you need to turn this safety feature off,
set :attr:`~email.policy.Policy.verify_generated_headers`.
(Contributed by Bas Bloemsaat and Petr Viktorin in :gh:`121650`.)
151 changes: 142 additions & 9 deletions Lib/email/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
specialsre = re.compile(r'[][\\()<>@,:;".]')
escapesre = re.compile(r'[\\"]')

def _has_surrogates(s):
"""Return True if s may contain surrogate-escaped binary data."""
# This check is based on the fact that unless there are surrogates, utf8
Expand Down Expand Up @@ -106,12 +107,127 @@ def formataddr(pair, charset='utf-8'):
return address



def getaddresses(fieldvalues):
"""Return a list of (REALNAME, EMAIL) for each fieldvalue."""
all = COMMASPACE.join(str(v) for v in fieldvalues)
a = _AddressList(all)
return a.addresslist


def _format_timetuple_and_zone(timetuple, zone):
Expand Down @@ -205,16 +321,33 @@ def parsedate_to_datetime(data):
tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))


def parseaddr(addr):
"""
Parse addr into its constituent realname and email address parts.

Return a tuple of realname and email address, unless the parse fails, in
which case return a 2-tuple of ('', '').
"""
addrs = _AddressList(addr).addresslist
if not addrs:
return '', ''
return addrs[0]


Expand Down
Loading
Toggle all file notes Toggle all file annotations