Skip to content

Commit 0db8dab

Browse files
Licht-Tserhiy-storchaka
authored andcommitted
pythongh-77749: Fix inconsistent behavior of non-ASCII handling in EmailPolicy.fold() (pythonGH-6986)
It now always encodes non-ASCII characters in headers if utf8 is false. Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 73d0a8b commit 0db8dab

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

Lib/email/policy.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -210,8 +210,15 @@ def _fold(self, name, value, refold_binary=False):
210210
self.refold_source == 'long' and
211211
(lines and len(lines[0])+len(name)+2 > maxlen or
212212
any(len(x) > maxlen for x in lines[1:])))
213-
if refold or refold_binary and _has_surrogates(value):
213+
214+
if not refold:
215+
if not self.utf8:
216+
refold = not value.isascii()
217+
elif refold_binary:
218+
refold = _has_surrogates(value)
219+
if refold:
214220
return self.header_factory(name, ''.join(lines)).fold(policy=self)
221+
215222
return name + ': ' + self.linesep.join(lines) + self.linesep
216223

217224

Lib/test/test_email/test_policy.py

+17
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,23 @@ def test_policy_addition(self):
135135
for attr, value in expected.items():
136136
self.assertEqual(getattr(added, attr), value)
137137

138+
def test_fold_utf8(self):
139+
expected_ascii = 'Subject: =?utf-8?q?=C3=A1?=\n'
140+
expected_utf8 = 'Subject: á\n'
141+
142+
msg = email.message.EmailMessage()
143+
s = 'á'
144+
msg['Subject'] = s
145+
146+
p_ascii = email.policy.default.clone()
147+
p_utf8 = email.policy.default.clone(utf8=True)
148+
149+
self.assertEqual(p_ascii.fold('Subject', msg['Subject']), expected_ascii)
150+
self.assertEqual(p_utf8.fold('Subject', msg['Subject']), expected_utf8)
151+
152+
self.assertEqual(p_ascii.fold('Subject', s), expected_ascii)
153+
self.assertEqual(p_utf8.fold('Subject', s), expected_utf8)
154+
138155
def test_fold_zero_max_line_length(self):
139156
expected = 'Subject: =?utf-8?q?=C3=A1?=\n'
140157

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:meth:`email.policy.EmailPolicy.fold` now always encodes non-ASCII characters
2+
in headers if :attr:`~email.policy.EmailPolicy.utf8` is false.

0 commit comments

Comments
 (0)