sumaq/backend/services/email_service.py

81 lines
3.7 KiB
Python

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"""
<html>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
<div style="max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px;">
<h2 style="color: #b45309;">Gestión de No Conformidades</h2>
<p>Estimado/a responsable,</p>
<p>Se le ha asignado una <strong>No Conformidad</strong> con la siguiente descripción:</p>
<blockquote style="background: #f9f9f9; border-left: 5px solid #ccc; padding: 10px; margin: 20px 0;">
{nc_description}
</blockquote>
<p>Por favor, haga clic en el siguiente enlace para revisar los detalles y registrar las acciones tomadas:</p>
<p style="text-align: center; margin: 30px 0;">
<a href="{link}" style="background-color: #b45309; color: white; padding: 12px 25px; text-decoration: none; border-radius: 5px; font-weight: bold;">
Revisar No Conformidad
</a>
</p>
<p style="font-size: 0.8em; color: #777;">Si el botón no funciona, copie y pegue el siguiente enlace en su navegador:<br>{link}</p>
<hr style="border: 0; border-top: 1px solid #eee; margin: 30px 0;">
<p style="font-size: 0.9em;">Este es un mensaje automático, por favor no responda directamente.</p>
</div>
</body>
</html>
"""
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