How can I get an attached eml file from email message content using Python?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities
--
Chapters
00:00 How Can I Get An Attached Eml File From Email Message Content Using Python?
00:55 Answer 1 Score 2
01:14 Accepted Answer Score 1
01:54 Thank you
--
Full question
https://stackoverflow.com/questions/5899...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #python37 #imaplib
#avk47
    Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities
--
Chapters
00:00 How Can I Get An Attached Eml File From Email Message Content Using Python?
00:55 Answer 1 Score 2
01:14 Accepted Answer Score 1
01:54 Thank you
--
Full question
https://stackoverflow.com/questions/5899...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #python37 #imaplib
#avk47
ANSWER 1
Score 2
Use eml_parser https://pypi.org/project/eml-parser/
import datetime
import json
import eml_parser
def json_serial(obj):
    if isinstance(obj, datetime.datetime):
        serial = obj.isoformat()
        return serial
with open('sample.eml', 'rb') as fhdl:
    raw_email = fhdl.read()
parsed_eml = eml_parser.eml_parser.decode_email_b(raw_email)
print(json.dumps(parsed_eml, default=json_serial))
ACCEPTED ANSWER
Score 1
Just to explain why this is happening (it hit me too), quoting the v. 3.5 library doc. (v2 says the same):
If the message is a multipart and the decode flag is True, then None is returned.
If your attachment is an .EML, it's almost always going to be multi-part, thus the None.
Jin Thakur's workaround is appropriate if you're only expecting .EML multipart attachments (not sure if there is any other use cases); it should have been accepted as an answer.