diff --git a/Lib/email/parser.py b/Lib/email/parser.py --- a/Lib/email/parser.py +++ b/Lib/email/parser.py @@ -100,9 +100,9 @@ meaning it parses the entire contents of the file. """ fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape') - with fp: - return self.parser.parse(fp, headersonly) - + msg = self.parser.parse(fp, headersonly) + fp.detach() + return msg def parsebytes(self, text, headersonly=False): """Create a message structure from a byte string. diff --git a/Lib/test/test_email/test_email.py b/Lib/test/test_email/test_email.py --- a/Lib/test/test_email/test_email.py +++ b/Lib/test/test_email/test_email.py @@ -2268,16 +2268,18 @@ self.assertEqual(text, s.getvalue()) def test_message_from_file(self): - with openfile('msg_01.txt') as fp: - text = fp.read() - fp.seek(0) - msg = email.message_from_file(fp) - s = StringIO() - # Don't wrap/continue long headers since we're trying to test - # idempotency. - g = Generator(s, maxheaderlen=0) - g.flatten(msg) - self.assertEqual(text, s.getvalue()) + fp = openfile('msg_01.txt') + text = fp.read() + fp.seek(0) + msg = email.parser.Parser().parse(fp) + self.assertFalse(fp.closed) + fp.close() + s = StringIO() + # Don't wrap/continue long headers since we're trying to test + # idempotency. + g = Generator(s, maxheaderlen=0) + g.flatten(msg) + self.assertEqual(text, s.getvalue()) def test_message_from_string_with_class(self): unless = self.assertTrue @@ -3181,9 +3183,11 @@ self.addCleanup(unlink, fn) with open(fn, 'wb') as testfile: testfile.write(self.non_latin_bin_msg) - with open(fn, 'rb') as testfile: - m = email.parser.BytesParser().parse(testfile) + fp = open(fn, 'rb') + m = email.parser.BytesParser().parse(fp) + self.assertFalse(fp.closed) self.assertEqual(str(m), self.non_latin_bin_msg_as7bit) + fp.close() latin_bin_msg = textwrap.dedent("""\ From: foo@bar.com