From 2c35a42e6025cb944b089311007e236e300eb733 Mon Sep 17 00:00:00 2001 From: Jeny Sadadia Date: Thu, 28 Dec 2023 13:09:40 +0530 Subject: [PATCH] api.email_sender: catch SMTP related exception Add `try-catch` block to `EmailSender._send_email` method to catch exception while sending emails. Signed-off-by: Jeny Sadadia --- api/email_sender.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/api/email_sender.py b/api/email_sender.py index 29857a38..5da61d0f 100644 --- a/api/email_sender.py +++ b/api/email_sender.py @@ -11,6 +11,7 @@ import email import email.mime.text import smtplib +from fastapi import HTTPException, status from .config import EmailSettings @@ -47,10 +48,17 @@ def _create_email(self, email_subject, email_content, email_recipient): def _send_email(self, email_msg): """Method to send an email message using SMTP""" - smtp = self._smtp_connect() - if smtp: - smtp.send_message(email_msg) - smtp.quit() + try: + smtp = self._smtp_connect() + if smtp: + smtp.send_message(email_msg) + smtp.quit() + except Exception as exc: + print(f"Error in sending email: {str(exc)}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to send email" + )from exc def create_and_send_email(self, email_subject, email_content, email_recipient):