# 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