diff --git a/app/utils/email_alerts.py b/app/utils/email_alerts.py index fdc23752..4505594a 100644 --- a/app/utils/email_alerts.py +++ b/app/utils/email_alerts.py @@ -36,7 +36,15 @@ def send_email_alert(subject: str, body: str) -> None: return sender_email = EMAIL_SENDER - receiver_emails = EMAIL_RECIPIENTS.split(",") + receiver_emails = [ + recipient.strip() + for recipient in EMAIL_RECIPIENTS.split(",") + if recipient.strip() + ] + + if not receiver_emails: + logging.warning("No valid email recipients configured.") + return message = MIMEMultipart() message["From"] = sender_email diff --git a/tests/test_email_alerts.py b/tests/test_email_alerts.py index 7b45953f..b00f376f 100644 --- a/tests/test_email_alerts.py +++ b/tests/test_email_alerts.py @@ -30,7 +30,7 @@ def test_send_email_alert_enabled(self): patch("app.utils.email_alerts.EMAIL_SENDER", "sender@example.com"), patch( "app.utils.email_alerts.EMAIL_RECIPIENTS", - "r1@example.com,r2@example.com", + " r1@example.com , , r2@example.com , ", ), patch("app.utils.email_alerts.EMAIL_SMTP_SERVER", "smtp.example.com"), patch("app.utils.email_alerts.EMAIL_SMTP_PORT", "587"), @@ -49,6 +49,28 @@ def test_send_email_alert_enabled(self): self.assertEqual(args[1], ["r1@example.com", "r2@example.com"]) self.assertIn("Subject: Subject", args[2]) self.assertIn("Body", args[2]) + self.assertIn("To: r1@example.com, r2@example.com", args[2]) + + def test_send_email_alert_no_valid_recipients(self): + smtp_mock = MagicMock() + mock_cm = MagicMock() + mock_cm.__enter__.return_value = smtp_mock + with ( + patch("smtplib.SMTP", return_value=mock_cm) as mock_smtp, + patch("app.utils.email_alerts.EMAIL_ENABLED", "True"), + patch("app.utils.email_alerts.EMAIL_SENDER", "sender@example.com"), + patch("app.utils.email_alerts.EMAIL_RECIPIENTS", " , ,, "), + patch("app.utils.email_alerts.EMAIL_SMTP_SERVER", "smtp.example.com"), + patch("app.utils.email_alerts.EMAIL_SMTP_PORT", "587"), + patch("app.utils.email_alerts.EMAIL_SMTP_TIMEOUT", 5), + patch("app.utils.email_alerts.EMAIL_USE_TLS", "false"), + patch("app.utils.email_alerts.EMAIL_USERNAME", "user"), + patch("app.utils.email_alerts.EMAIL_PASSWORD", "pass"), + patch("logging.warning") as mock_warning, + ): + send_email_alert("Subject", "Body") + mock_warning.assert_called_once_with("No valid email recipients configured.") + mock_smtp.assert_not_called() def test_send_email_alert_timeout(self): smtp_mock = MagicMock()