import smtplib import os from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header from dotenv import load_dotenv load_dotenv() class EmailService: @staticmethod def send_nc_notification(email: str, access_hash: str, nc_description: str): smtp_host = os.getenv("SMTP_HOST", "smtp.gmail.com") smtp_port = int(os.getenv("SMTP_PORT", 587)) smtp_user = os.getenv("SMTP_USER") smtp_password = os.getenv("SMTP_PASSWORD") from_name = os.getenv("EMAILS_FROM_NAME", "Sistema de Supervisión") from_email = os.getenv("EMAILS_FROM_EMAIL", smtp_user) frontend_url = os.getenv("FRONTEND_URL", "http://localhost:4200") if not smtp_user or not smtp_password: print("WARNING: Email credentials not configured. Simulation mode.") return EmailService._simulate_send(email, access_hash, nc_description, frontend_url) subject = "Acción Requerida: No Conformidad Asignada" link = f"{frontend_url}/nc-guest/{access_hash}" body = f"""

Gestión de No Conformidades

Estimado/a responsable,

Se le ha asignado una No Conformidad con la siguiente descripción:

{nc_description}

Por favor, haga clic en el siguiente enlace para revisar los detalles y registrar las acciones tomadas:

Revisar No Conformidad

Si el botón no funciona, copie y pegue el siguiente enlace en su navegador:
{link}


Este es un mensaje automático, por favor no responda directamente.

""" msg = MIMEMultipart() msg['From'] = f"{Header(from_name, 'utf-8').encode()} <{from_email}>" msg['To'] = email msg['Subject'] = Header(subject, 'utf-8') msg.attach(MIMEText(body, 'html', 'utf-8')) try: server = smtplib.SMTP(smtp_host, smtp_port) server.starttls() server.login(smtp_user, smtp_password) text = msg.as_string() server.sendmail(from_email, email, text) server.quit() print(f"Email sent successfully to {email}") return True except Exception as e: print(f"Error sending email: {str(e)}") return False @staticmethod def _simulate_send(email: str, access_hash: str, nc_description: str, frontend_url: str): link = f"{frontend_url}/nc-guest/{access_hash}" print(f"================ SIMULATION ================") print(f"TO: {email}") print(f"LINK: {link}") print(f"DESC: {nc_description}") print(f"============================================") return True