Effectivement, c'est bien lié au format DOS et les retours à la ligne qui sèment la zizanie. J'ajoute que l'encodage utf-8 semble également poser des problèmes et qu'il vaut mieux encoder le tout en ASCII pour le parsing (ce que semble faire dos2unix).
En python si tu ne veux pas utiliser l'utilitaire tu peux faire comme ça.
# parsing_eml_files.py
import os.path
from email import policy
from email.parser import BytesParser
EMAIL_FILE = "./00035646.eml"
def dos2unix(filepath):
"""Convert DOS file to Unix file (remove CRLF line terminators)"""
with open(filepath, mode="r") as file:
path, extension = os.path.splitext(filepath)
content = file.read().replace('\r\n', '\n')
new_file = f"{path}_unix{extension}"
with open(new_file, mode="w", encoding="ASCII", errors="ignore") as write_file:
write_file.write(content)
return new_file
if __name__ == "__main__":
with open(dos2unix(EMAIL_FILE), "rb") as fp:
msg = BytesParser(policy=policy.default).parse(fp)
print("To:", msg["to"])
print("From:", msg["from"])
print("Subject:", msg["subject"])
Tu auras un fichier qui se terminera par _unix.eml (libre à toi de le supprimer ensuite ou pas). Le mieux est peut être de convertir chaque mail au format Unix avant le parsing.
Le script retourne:
To: mjs <mjs-86@googlegroups.com>
From: romain sling <romain.sling@gmail.com>
Subject: Re: tract formule H