How can I get an attached eml file from email message content using Python?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over
--
Chapters
00:00 Question
01:35 Accepted answer (Score 1)
02:20 Answer 2 (Score 1)
02:44 Thank you
--
Full question
https://stackoverflow.com/questions/5899...
Answer 1 links:
https://pypi.org/project/eml-parser/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #python37 #imaplib
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over
--
Chapters
00:00 Question
01:35 Accepted answer (Score 1)
02:20 Answer 2 (Score 1)
02:44 Thank you
--
Full question
https://stackoverflow.com/questions/5899...
Answer 1 links:
https://pypi.org/project/eml-parser/
--
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.