EmailCrono/utils/attachment_handler.py

34 lines
900 B
Python
Raw Normal View History

2025-02-05 08:14:36 -03:00
# utils/attachment_handler.py
import os
import hashlib
import re
def guardar_adjunto(parte, dir_adjuntos):
nombre = parte.get_filename()
if not nombre:
return None
nombre = re.sub(r'[<>:"/\\|?*]', '_', nombre)
ruta = os.path.join(dir_adjuntos, nombre)
if os.path.exists(ruta):
contenido_nuevo = parte.get_payload(decode=True)
hash_nuevo = hashlib.md5(contenido_nuevo).hexdigest()
with open(ruta, 'rb') as f:
hash_existente = hashlib.md5(f.read()).hexdigest()
if hash_nuevo == hash_existente:
return ruta
base, ext = os.path.splitext(nombre)
i = 1
while os.path.exists(ruta):
ruta = os.path.join(dir_adjuntos, f"{base}_{i}{ext}")
i += 1
with open(ruta, 'wb') as f:
f.write(parte.get_payload(decode=True))
return ruta