: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
feat(alerts): centralize email delivery (#71600)
Matt Pua81a03b40e219
diff --git a/posthog/tasks/alerts/test/test_alert_subscriptions.py b/posthog/tasks/alerts/test/test_alert_subscriptions.pyindex eee1fffb7a13..b2484cd3330e 100644--- a/posthog/tasks/alerts/test/test_alert_subscriptions.py+++ b/posthog/tasks/alerts/test/test_alert_subscriptions.py@@ -8,7 +8,7 @@ from posthog.api.test.dashboards import DashboardAPIfrom posthog.models import Userfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.organization import Organization, OrganizationMembership-from posthog.tasks.alerts.utils import send_notifications_for_breaches+from posthog.tasks.alerts.utils import send_notifications_for_breaches, send_notifications_for_disabledfrom posthog.tasks.test.utils_email_tests import mock_email_messagesfrom products.alerts.backend.models import AlertConfiguration, AlertSubscription@@ -65,7 +65,7 @@ class TestAlertSubscriptionOrgMembership(APIBaseTest):assert not AlertSubscription.objects.filter(alert_configuration=alert, user=self.other_user).exists()assert AlertSubscription.objects.filter(alert_configuration=alert, user=self.user).exists()- @patch("posthog.tasks.alerts.utils.EmailMessage")+ @patch("products.alerts.backend.email_notifications.EmailMessage")def test_send_notifications_excludes_removed_members(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)alert = AlertConfiguration.objects.get(pk=self.alert["id"])@@ -180,7 +180,7 @@ class TestAlertEmailNotifications(APIBaseTest):},).json()- @patch("posthog.tasks.alerts.utils.EmailMessage")+ @patch("products.alerts.backend.email_notifications.EmailMessage")def test_send_emails(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)alert = AlertConfiguration.objects.get(pk=self.alert["id"])@@ -194,3 +194,16 @@ class TestAlertEmailNotifications(APIBaseTest):assert email.to[0]["recipient"] == "[email protected]"assert "first anomaly description" in email.html_bodyassert "second anomaly description" in email.html_body++ @patch("products.alerts.backend.email_notifications.EmailMessage")+ def test_send_disabled_email(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ alert = AlertConfiguration.objects.get(pk=self.alert["id"])++ send_notifications_for_disabled(alert, "Insight query is invalid", [self.user.email])++ assert len(mocked_email_messages) == 1+ email = mocked_email_messages[0]+ assert email.template_name == "alert_disabled"+ assert email.to[0]["recipient"] == "[email protected]"+ assert "Insight query is invalid" in email.html_bodydiff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex e39609346fe2..224fa0621cf4 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -10,10 +10,10 @@ from dateutil.relativedelta import MO, relativedeltafrom posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQueryfrom posthog.cdp.internal_events import InternalEventEvent, produce_internal_event-from posthog.email import EmailMessagefrom posthog.exceptions_capture import capture_exceptionfrom posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restriction+from products.alerts.backend.facade.api import send_alert_emailfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, derive_detector_event_fieldslogger = structlog.get_logger(__name__)@@ -231,7 +231,9 @@ def send_notifications_for_breaches(campaign_key = f"alert-firing-notification-{idempotency_key}"insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"alert_url = f"{insight_url}?alert_id={alert.id}"- message = EmailMessage(+ logger.info("send_notifications_for_breaches", alert_id=alert.id, anomaly_count=len(breaches))+ send_alert_email(+ recipients=email_targets,campaign_key=campaign_key,subject=subject,template_name="alert_check_firing",@@ -245,12 +247,6 @@ def send_notifications_for_breaches(},)- for target in email_targets:- message.add_recipient(email=target)-- logger.info("send_notifications_for_breaches", alert_id=alert.id, anomaly_count=len(breaches))- message.send()-# 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.trigger_alert_hog_functions(alert=alert, properties={"breaches": "\n".join(breaches), **(extra_properties or {})})@@ -437,7 +433,8 @@ def send_notifications_for_disabled(alert: AlertConfiguration, reason: str, targcampaign_key = f"alert-disabled-notification-{alert.id}-{timezone.now().timestamp()}"insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"alert_url = f"{insight_url}?alert_id={alert.id}"- message = EmailMessage(+ send_alert_email(+ recipients=targets,campaign_key=campaign_key,subject=subject,template_name="alert_disabled",@@ -450,7 +447,3 @@ def send_notifications_for_disabled(alert: AlertConfiguration, reason: str, targ"project_name": alert.team.name,},)- for target in targets:- message.add_recipient(email=target)-- message.send()diff --git a/products/alerts/backend/email_notifications.py b/products/alerts/backend/email_notifications.pynew file mode 100644index 000000000000..fab4120f4b3a--- /dev/null+++ b/products/alerts/backend/email_notifications.py@@ -0,0 +1,22 @@+from collections.abc import Collection++from posthog.email import EmailMessage+++def send_alert_email(+ *,+ recipients: Collection[str],+ campaign_key: str,+ subject: str,+ template_name: str,+ template_context: dict[str, object],+) -> None:+ message = EmailMessage(+ campaign_key=campaign_key,+ subject=subject,+ template_name=template_name,+ template_context=template_context,+ )+ for recipient in recipients:+ message.add_recipient(email=recipient)+ message.send()diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.pyindex 27426ea4c853..295463e422b6 100644--- a/products/alerts/backend/facade/api.py+++ b/products/alerts/backend/facade/api.py@@ -11,6 +11,7 @@ from products.alerts.backend.destinations import (soft_delete_alert_destinations,soft_delete_all_alert_destinations,)+from products.alerts.backend.email_notifications import send_alert_email__all__ = ["DESTINATION_TEMPLATE_IDS",@@ -21,5 +22,6 @@ __all__ = ["create_alert_destination_hog_functions","soft_delete_alert_destinations","soft_delete_all_alert_destinations",+ "send_alert_email","validate_destination_data",]diff --git a/products/alerts/backend/test/test_email_notifications.py b/products/alerts/backend/test/test_email_notifications.pynew file mode 100644index 000000000000..eb54278f0cfb--- /dev/null+++ b/products/alerts/backend/test/test_email_notifications.py@@ -0,0 +1,41 @@+from unittest.mock import MagicMock, call, patch++from products.alerts.backend.email_notifications import send_alert_email+++@patch("products.alerts.backend.email_notifications.EmailMessage")+def test_send_alert_email_delivers_to_every_recipient(MockEmailMessage: MagicMock) -> None:+ send_alert_email(+ recipients=("[email protected]", "[email protected]"),+ campaign_key="alert-email-test",+ subject="Alert firing",+ template_name="alert_check_firing",+ template_context={+ "match_descriptions": ["Threshold breached"],+ "insight_url": "/project/1/insights/example",+ "insight_name": "Example insight",+ "alert_url": "/project/1/insights/example?alert_id=1",+ "alert_name": "Example alert",+ "project_name": "Example project",+ },+ )++ MockEmailMessage.assert_called_once_with(+ campaign_key="alert-email-test",+ subject="Alert firing",+ template_name="alert_check_firing",+ template_context={+ "match_descriptions": ["Threshold breached"],+ "insight_url": "/project/1/insights/example",+ "insight_name": "Example insight",+ "alert_url": "/project/1/insights/example?alert_id=1",+ "alert_name": "Example alert",+ "project_name": "Example project",+ },+ )+ message = MockEmailMessage.return_value+ assert message.add_recipient.call_args_list == [+ call(email="[email protected]"),+ call(email="[email protected]"),+ ]+ message.send.assert_called_once_with()