Skip to content

Commit bf4c234

Browse files
pythongh-110501: Strip any line ending from the mbox "From " line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dcf9087 commit bf4c234

3 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎Lib/mailbox.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -841,7 +841,7 @@ def get_message(self, key):
841841
"""Return a Message representation or raise a KeyError."""
842842
start, stop = self._lookup(key)
843843
self._file.seek(start)
844-
from_line = self._file.readline().replace(linesep, b'').decode('ascii')
844+
from_line = self._file.readline().rstrip(b'\r\n').decode('ascii')
845845
string = self._file.read(stop - self._file.tell())
846846
msg = self._message_factory(string.replace(linesep, b'\n'))
847847
msg.set_unixfrom(from_line)

‎Lib/test/test_mailbox.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from test.support import requires_root_user
1515
from test.support import socket_helper
1616
import unittest
17+
from unittest import mock
1718
import textwrap
1819
import mailbox
1920
import glob
@@ -1313,6 +1314,25 @@ def test_terminating_newline(self):
13131314
message = self._box.get(i)
13141315
self.assertEqual(message.get_payload(), 'No newline at the end\n')
13151316

1317+
def test_from_line_with_other_line_endings(self):
1318+
# gh-110501: The line ending must be removed from the "From " line
1319+
# even if the file uses line endings other than os.linesep.
1320+
path = self._path + '.other-eol'
1321+
self.addCleanup(os_helper.unlink, path)
1322+
for file_eol, linesep in ((b'\n', b'\r\n'), (b'\r\n', b'\n')):
1323+
with self.subTest(file_eol=file_eol, linesep=linesep):
1324+
with open(path, 'wb') as f:
1325+
f.write(file_eol.join([b'From foo@bar blah', b'From: foo',
1326+
b'', b'0', b'']))
1327+
with mock.patch.object(mailbox, 'linesep', linesep):
1328+
box = mailbox.mbox(path)
1329+
try:
1330+
msg = box[0]
1331+
finally:
1332+
box.close()
1333+
self.assertEqual(msg.get_unixfrom(), 'From foo@bar blah')
1334+
self.assertEqual(msg.get_from(), 'foo@bar blah')
1335+
13161336
def test_message_separator(self):
13171337
# Check there's always a single blank line after each message
13181338
self._box.add('From: foo\n\n0') # No newline at the end
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :class:`mailbox.mbox` and :class:`mailbox.MMDF` keeping a trailing line
2+
ending in the "From " line of a message when the mailbox file uses line
3+
endings other than :data:`os.linesep`.

0 commit comments

Comments
 (0)