:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(alerts): skip alert emails when the instance has no email (#119112)
posthog[bot]8dfbe960f2f6
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.pyindex 9b3d8fd170e5..841c27fb93a9 100644--- a/posthog/tasks/alerts/test/test_utils.py+++ b/posthog/tasks/alerts/test/test_utils.py@@ -1,3 +1,4 @@+from collections.abc import Callablefrom datetime import UTC, datetimefrom functools import partial@@ -19,6 +20,7 @@ from posthog.tasks.alerts.utils import (dispatch_alert_notification,next_check_time,send_notifications_for_breaches,+ send_notifications_for_disabled,send_notifications_for_errors,trigger_alert_hog_functions,)@@ -294,6 +296,25 @@ class TestSendNotificationsReceipts(APIBaseTest):assert [(r.channel, r.target, r.status) for r in receipts] == [("email", self.user.email, "accepted")]mock_send.assert_called_once()+ @parameterized.expand(+ [+ ("breaches", lambda alert: send_notifications_for_breaches(alert, ["breach"], idempotency_key="check-1")),+ ("errors", lambda alert: send_notifications_for_errors(alert, {"message": "boom"}, idempotency_key="c-1")),+ (+ "disabled",+ lambda alert: send_notifications_for_disabled(alert, "bad config", [alert.created_by.email]),+ ),+ ]+ )+ @patch("posthog.tasks.alerts.utils.trigger_alert_hog_functions", return_value=[])+ @patch("products.alerts.backend.facade.email.EmailMessage")+ @patch("products.alerts.backend.facade.email.is_email_available", return_value=False)+ def test_notifications_skip_email_when_instance_has_no_email(+ self, _name: str, send: Callable, _mock_available: MagicMock, mock_message: MagicMock, _mock_trigger: MagicMock+ ) -> None:+ assert send(self.alert) == []+ mock_message.assert_not_called()+class TestDispatchAlertInsightChart(APIBaseTest):def setUp(self) -> None:diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex fe610b849b5a..854eeaef98b5 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -280,7 +280,7 @@ def send_notifications_for_breaches(insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"alert_url = f"{insight_url}?alert_id={alert.id}"logger.info("send_notifications_for_breaches", alert_id=alert.id, anomaly_count=len(breaches))- send_alert_email(+ email_sent = send_alert_email(recipients=email_targets,campaign_key=campaign_key,subject=subject,@@ -294,8 +294,9 @@ def send_notifications_for_breaches("project_name": alert.team.name,},)- accepted_at = datetime.now(UTC).isoformat()- deliveries.extend(AlertDelivery(channel="email", target=target, at=accepted_at) for target in email_targets)+ if email_sent:+ accepted_at = datetime.now(UTC).isoformat()+ deliveries.extend(AlertDelivery(channel="email", target=target, at=accepted_at) for target in email_targets)# Join with newlines so each breach/investigation line renders on its own line in# Slack/Discord/Teams destinations rather than as one run-on comma-separated string.@@ -309,9 +310,9 @@ def send_notifications_for_breaches(return deliveries-def send_test_alert_email(alert: AlertConfiguration, recipients: Collection[str], idempotency_key: str) -> None:+def send_test_alert_email(alert: AlertConfiguration, recipients: Collection[str], idempotency_key: str) -> bool:insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"- send_alert_email(+ return send_alert_email(recipients=recipients,campaign_key=f"alert-test-notification-{idempotency_key}",subject=f"Test alert: {alert.name} for {alert.team.name}",@@ -339,7 +340,7 @@ def send_notifications_for_errors(alert: AlertConfiguration, error: dict, idempoerror_message = str(error.get("message") or "Unknown error").strip()[:1000] or "Unknown error"insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"alert_url = f"{insight_url}?alert_id={alert.id}"- send_alert_email(+ email_sent = send_alert_email(recipients=email_targets,campaign_key=f"alert-evaluation-failed-notification-{idempotency_key}",subject=f"PostHog could not evaluate {subject_alert_name}",@@ -356,6 +357,8 @@ def send_notifications_for_errors(alert: AlertConfiguration, error: dict, idempo"detector_unavailable": error.get("code") == LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,},)+ if not email_sent:+ return []accepted_at = datetime.now(UTC).isoformat()return [AlertDelivery(channel="email", target=target, at=accepted_at) for target in email_targets]@@ -855,7 +858,7 @@ def send_notifications_for_disabled(campaign_key = f"alert-disabled-notification-{alert.id}-{idempotency_key or timezone.now().timestamp()}"insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"alert_url = f"{insight_url}?alert_id={alert.id}"- send_alert_email(+ email_sent = send_alert_email(recipients=targets,campaign_key=campaign_key,subject=subject,@@ -869,5 +872,7 @@ def send_notifications_for_disabled("project_name": alert.team.name,},)+ if not email_sent:+ return []accepted_at = datetime.now(UTC).isoformat()return [AlertDelivery(channel="email", target=target, at=accepted_at) for target in targets]diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 2c0308da2236..3066ab777059 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -1249,7 +1249,7 @@ class TestEvaluateAlert:alert_id=str(alert_with_user.id), alert_check_id=result.alert_check_id)with patch(- "posthog.tasks.alerts.utils.send_alert_email", side_effect=[RuntimeError("Mail is unavailable"), None]+ "posthog.tasks.alerts.utils.send_alert_email", side_effect=[RuntimeError("Mail is unavailable"), True]) as mock_email:with pytest.raises(RuntimeError, match="Mail is unavailable"):await env.run(notify_alert, notify_inputs)diff --git a/products/alerts/backend/facade/email.py b/products/alerts/backend/facade/email.pyindex 83b3d0a306a1..a8bbf2ac59c8 100644--- a/products/alerts/backend/facade/email.py+++ b/products/alerts/backend/facade/email.py@@ -5,10 +5,14 @@ from __future__ import annotationsfrom collections.abc import Collectionfrom uuid import UUID-from posthog.email import EmailMessage+import structlog++from posthog.email import EmailMessage, is_email_availablefrom products.alerts.backend.logic import alert_email+logger = structlog.get_logger(__name__)+def send_alert_email(*,@@ -17,8 +21,11 @@ def send_alert_email(subject: str,template_name: str,template_context: dict[str, object],-) -> None:- """Send one alert email to every recipient."""+) -> bool:+ """Send one alert email to every recipient. Returns False and sends nothing when the instance has no email."""+ if not is_email_available():+ logger.info("Skipping alert email because email is not available", campaign_key=campaign_key)+ return Falsemessage = EmailMessage(campaign_key=campaign_key,subject=subject,@@ -28,6 +35,7 @@ def send_alert_email(for recipient in recipients:message.add_recipient(email=recipient)message.send()+ return Truedef alert_email_recipients(*, team_id: int, alert_id: UUID) -> list[tuple[int, str]]:diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.pyindex 38237895ba8d..389a970defe2 100644--- a/products/alerts/backend/presentation/views/alert.py+++ b/products/alerts/backend/presentation/views/alert.py@@ -1837,8 +1837,10 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):email_delivery_unavailable = bool(email_targets) and not is_email_available()if email_targets:try:- send_test_alert_email(alert, recipients=email_targets, idempotency_key=str(uuid.uuid4()))- successful_email_count = len(email_targets)+ if send_test_alert_email(alert, recipients=email_targets, idempotency_key=str(uuid.uuid4())):+ successful_email_count = len(email_targets)+ else:+ failed_delivery_channels.append("email")except Exception as error:capture_exception(error,diff --git a/products/alerts/backend/test/test_email_notifications.py b/products/alerts/backend/test/test_email_notifications.pyindex afcaa678239f..ff559331cbec 100644--- a/products/alerts/backend/test/test_email_notifications.py+++ b/products/alerts/backend/test/test_email_notifications.py@@ -5,9 +5,10 @@ from django.template.loader import render_to_stringfrom products.alerts.backend.facade.email import send_alert_email+@patch("products.alerts.backend.facade.email.is_email_available", return_value=True)@patch("products.alerts.backend.facade.email.EmailMessage")-def test_send_alert_email_delivers_to_every_recipient(MockEmailMessage: MagicMock) -> None:- send_alert_email(+def test_send_alert_email_delivers_to_every_recipient(MockEmailMessage: MagicMock, _mock_available: MagicMock) -> None:+ assert send_alert_email(recipients=("[email protected]", "[email protected]"),campaign_key="alert-email-test",subject="Alert firing",diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex d8d17299e423..4a5c237113ca 100644--- a/products/alerts/backend/tests/api/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -2041,8 +2041,9 @@ class TestAlertTestDelivery(TrendsInsightAPITest):@mock.patch("products.alerts.backend.presentation.views.alert.trigger_alert_hog_functions")@mock.patch("products.alerts.backend.facade.email.EmailMessage")+ @mock.patch("products.alerts.backend.facade.email.is_email_available", return_value=True)def test_sends_test_delivery_to_subscribed_users_without_a_destination(- self, mock_email_message, mock_trigger+ self, _mock_available, mock_email_message, mock_trigger) -> None:alert = AlertConfiguration.objects.get(id=self.alert["id"])AlertSubscription.objects.create(alert_configuration=alert, user=self.user)@@ -2062,12 +2063,10 @@ class TestAlertTestDelivery(TrendsInsightAPITest):mock_trigger.assert_not_called()@mock.patch("products.alerts.backend.presentation.views.alert.is_email_available", return_value=False)- @mock.patch(- "products.alerts.backend.presentation.views.alert.send_test_alert_email",- side_effect=RuntimeError("email unavailable"),- )+ @mock.patch("products.alerts.backend.facade.email.is_email_available", return_value=False)+ @mock.patch("products.alerts.backend.facade.email.EmailMessage")def test_returns_email_unavailable_when_email_delivery_is_not_configured(- self, _mock_email, _mock_available+ self, mock_email_message, _mock_facade_available, _mock_view_available) -> None:alert = AlertConfiguration.objects.get(id=self.alert["id"])AlertSubscription.objects.create(alert_configuration=alert, user=self.user)@@ -2078,6 +2077,7 @@ class TestAlertTestDelivery(TrendsInsightAPITest):assert response.json() == {"detail": "Email delivery is unavailable for this instance. Configure email settings before trying again."}+ mock_email_message.assert_not_called()@mock.patch("products.alerts.backend.presentation.views.alert.send_test_alert_email",