Bladeren bron

Deploy desde script deploy.sh

latapp 9 maanden geleden
bovenliggende
commit
5a9b42436d
4 gewijzigde bestanden met toevoegingen van 75 en 27 verwijderingen
  1. 5 3
      app.py
  2. 2 0
      config/settings.py
  3. 1 1
      routes/chat.py
  4. 67 23
      services/email_service.py

+ 5 - 3
app.py

@@ -3,14 +3,16 @@ from fastapi.middleware.cors import CORSMiddleware
 from starlette.middleware.sessions import SessionMiddleware
 from config.settings import SECRET_KEY
 from routes import sales
-
-
+from services.email_service import initialize_email_sender
 
 def create_app() -> FastAPI:
     """Create and configure FastAPI application"""
     app = FastAPI(title="Web Pedidos Klein - FastAPI Backend",
                   description="Backend for the Web Pedidos Klein application using FastAPI",)
-    
+
+    # Initialize email sender
+    initialize_email_sender()
+
     # Add CORS middleware
     app.add_middleware(
         CORSMiddleware,

+ 2 - 0
config/settings.py

@@ -9,6 +9,8 @@ load_dotenv()
 
 
 APPNAME = "Pedidos Express"
+MAIL = os.getenv("MAIL","")
+MAIL_PASSWORD = os.getenv("MAIL_PASSWORD","")
 LOGS_FOLDER = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs')
 if not os.path.exists(LOGS_FOLDER):
     os.makedirs(LOGS_FOLDER)

+ 1 - 1
routes/chat.py

@@ -28,4 +28,4 @@ async def chat_completions(request_data: ChatCompletionRequest, request: Request
         raise e
     except Exception as e:
         logger.error(f"Unexpected error in /api/chat/completions: {e}")
-        raise HTTPException(status_code=500, detail="Error interno del servidor al procesar el chat.")
+        raise HTTPException(status_code=500, detail="Error interno del servidor al procesar el chat.")

+ 67 - 23
services/email_service.py

@@ -1,30 +1,74 @@
+from config.settings import MAIL, MAIL_PASSWORD
 import smtplib
 from email.message import EmailMessage
 from logging import getLogger
-
+from contextlib import contextmanager
+from typing import Optional
 logger = getLogger(__name__)
 
-def send_email(
-    subject: str,
-    body: str,
-    to: list[str],
-    **kwargs
-):
-    logger.debug(str(kwargs))
-    """Send email """
-    # Datos del remitente
-    EMAIL_ORIGEN = 'expresspedidos211@gmail.com'
-    CONTRASENA = 'drkassszdtgapufg'
+email_sender = None
+class EmailSender:
+    def __init__(self, email: str, password: str):
+        self.email = email
+        self.password = password
+        self._smtp: Optional[smtplib.SMTP_SSL] = None
+        logger.debug(f"EmailSender initialized with {self.email}")
+
+    @contextmanager
+    def get_connection(self):
+        if self._smtp is None:
+            logger.info("Establishing new SMTP connection.")
+            try:
+                self._smtp = smtplib.SMTP_SSL('smtp.gmail.com', 465)
+                self._smtp.login(self.email, self.password)
+                logger.info("SMTP connection established and logged in.")
+            except Exception as e:
+                logger.error(f"Failed to establish SMTP connection: {e}")
+                raise
+        try:
+            yield self._smtp
+        except Exception as e:
+            logger.error(f"Error during SMTP operation: {e}")
+            self.close_connection()
+            raise e
+
+    def close_connection(self):
+        if self._smtp:
+            try:
+                logger.info("Closing SMTP connection.")
+                self._smtp.quit()
+                logger.info("SMTP connection closed.")
+            except Exception as e:
+                logger.warning(f"Error closing SMTP connection: {e}")
+            finally:
+                self._smtp = None
+
+    def send_email(self, subject: str, body: str, to: list[str], **kwargs):
+        logger.debug(f"Preparing to send email to: {to} with subject: '{subject}' and kwargs: {kwargs}")
+        
+        msg = EmailMessage()
+        msg['Subject'] = subject
+        msg['From'] = self.email
+        msg['To'] = ", ".join(to)
+        msg.set_content('Este correo tiene contenido HTML.')
+        msg.add_alternative(body.format(**kwargs), subtype='html')
+        
+        try:
+            with self.get_connection() as smtp:
+                smtp.send_message(msg)
+                logger.info(f"Email sent to {to} with subject '{subject}'.")
+        except Exception as e:
+            logger.error(f"Failed to send email to {to}: {e}")
+            raise
+
 
-    # Crear el correo
-    msg = EmailMessage()
-    msg['Subject'] = subject
-    msg['From'] = EMAIL_ORIGEN
-    msg['To'] = ", ".join(to)
-    msg.set_content('Este correo tiene contenido HTML.')
-    msg.add_alternative(body.format(**kwargs), subtype='html')
+def initialize_email_sender():
+    global email_sender
+    if email_sender is None:
+        email_sender = EmailSender(MAIL, MAIL_PASSWORD)
+        logger.info("EmailSender initialized globally.")
+    return email_sender
 
-    # Enviar el correo usando SMTP de Gmail
-    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
-        smtp.login(EMAIL_ORIGEN, CONTRASENA)
-        smtp.send_message(msg)
+def send_email(subject: str, body: str, to: list[str], **kwargs):
+    email_sender = initialize_email_sender()
+    email_sender.send_email(subject, body, to, **kwargs)