This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: email.message_from_bytes not working on BytesIO() object
Type: behavior Stage: resolved
Components: email Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: barry, cd311, eric.smith, r.david.murray
Priority: normal Keywords:

Created on 2021-08-09 11:49 by cd311, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg399259 - (view) Author: Christian Degenkolb (cd311) Date: 2021-08-09 11:49
Hi, 

the following minimal working example of the problem  

from io import BytesIO
from os import read
import email

fp = BytesIO()

with open('mail.eml', 'rb') as f:
    filecontent = f.read()
    print("type(filecontent)= ", type(filecontent))
    fp.write(filecontent)

mailobj = email.message_from_bytes(fp)

produces the following exception

$ python testparser.py 
type(filecontent)=  <class 'bytes'>
Traceback (most recent call last):
  File "testparser.py", line 16, in <module>
    mailobj = email.message_from_bytes(fp)
  File "/usr/lib/python3.8/email/__init__.py", line 46, in message_from_bytes
    return BytesParser(*args, **kws).parsebytes(s)
  File "/usr/lib/python3.8/email/parser.py", line 122, in parsebytes
    text = text.decode('ASCII', errors='surrogateescape')
AttributeError: '_io.BytesIO' object has no attribute 'decode'


This is a python 3.8.10 on an Ubuntu 20.04 LTS installed from the packages. 

The documentation for message_from_bytes https://docs.python.org/3.10/library/email.parser.html#email.message_from_bytes mentions bytes-like objects which links to https://docs.python.org/3.10/glossary.html#term-bytes-like-object and references object of type byte. 

Shouldn't this work with BytesIO()? A'm I missing something?

with regards
Christian
msg399262 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-08-09 13:11
Use filecontent.getvalue(): https://docs.python.org/3/library/io.html#io.BytesIO.getvalue
History
Date User Action Args
2022-04-11 14:59:48adminsetgithub: 89033
2021-08-09 13:11:33eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg399262

resolution: not a bug
stage: resolved
2021-08-09 11:49:52cd311create