: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(email): detect and recover from silent SMTP send failures (#66456)
Alex Lebedev3376fbae1bf0
diff --git a/posthog/email.py b/posthog/email.pyindex 490ab8cf0a54..c7c8aa9e3d4e 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -1,8 +1,6 @@-# ruff: noqa: T201 allow print statements--import sysimport htmlimport uuid+import smtplibimport datetimeimport dataclassesfrom decimal import Decimal@@ -20,10 +18,12 @@ from django.utils import timezonefrom django.utils.module_loading import import_stringimport requests+import structlogimport css_inlineimport posthoganalyticsfrom celery import shared_taskfrom lxml import html as lxml_html+from prometheus_client import Counterfrom posthog.celery_queues import CeleryQueuefrom posthog.exceptions_capture import capture_exception@@ -31,6 +31,8 @@ from posthog.helpers.email_utils import sanitize_email_stringfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.messaging import MessagingRecord+logger = structlog.get_logger(__name__)+def inline_css(value: str) -> str:"""@@ -89,6 +91,24 @@ EMAIL_TASK_KWARGS = {"retry_backoff": True,}+# Failure rate as an alertable time series. Labelled only by outcome+transport to bound+# cardinality (per-team volume lives in MessagingRecord); scraped via prometheus multiprocess.+EMAIL_SEND_COUNTER = Counter(+ "posthog_email_send_total",+ "Email send attempts by outcome (sent|failed) and transport (smtp|http).",+ labelnames=["outcome", "transport"],+)++# Retryable connection/network errors only. NOT bare OSError: every smtplib exception subclasses+# it, so OSError would also retry auth/recipient failures and re-hammer the relay's per-IP limit.+_TRANSIENT_SMTP_ERRORS = (+ smtplib.SMTPServerDisconnected,+ smtplib.SMTPConnectError,+ smtplib.SMTPHeloError,+ TimeoutError, # socket timeouts+ ConnectionError, # reset / refused / aborted+)+CUSTOMER_IO_TEMPLATE_ID_MAP = {# Set up in customer.io"2fa_enabled": "31",@@ -154,6 +174,8 @@ def _send_via_http("Authorization": f"Bearer {customerio_api_key}",}+ sent_count = 0+ already_sent_count = 0 # delivered in a prior run — not a failure if the batch later abortstry:for dest in to:with transaction.atomic():@@ -163,6 +185,7 @@ def _send_via_http(record = MessagingRecord.objects.select_for_update().get(pk=record.pk)if record.sent_at:+ already_sent_count += 1continueidentifiers: dict[str, str] = {"email": dest["raw_email"]}@@ -197,9 +220,14 @@ def _send_via_http(record.sent_at = timezone.now()record.save()+ EMAIL_SEND_COUNTER.labels(outcome="sent", transport="http").inc()+ sent_count += 1+except Exception as err:- print("Could not send email via http:", err, file=sys.stderr)- capture_exception(err)+ capture_exception(err) # already logs the traceback via logger.exception+ # Count every recipient that did not get through (the failing one + any not yet attempted),+ # so `failed` shares the per-recipient unit with `sent` instead of registering once per batch.+ EMAIL_SEND_COUNTER.labels(outcome="failed", transport="http").inc(len(to) - already_sent_count - sent_count)def _send_via_smtp(@@ -212,63 +240,85 @@ def _send_via_smtp(reply_to: Optional[str] = None,) -> None:"""Sends emails using SMTP"""- messages: list = []- records: list = []+ connection = None+ try:+ klass = import_string(settings.EMAIL_BACKEND) if settings.EMAIL_BACKEND else EmailBackend+ connection = klass(+ host=get_instance_setting("EMAIL_HOST"),+ port=get_instance_setting("EMAIL_PORT"),+ username=get_instance_setting("EMAIL_HOST_USER"),+ password=get_instance_setting("EMAIL_HOST_PASSWORD"),+ use_tls=get_instance_setting("EMAIL_USE_TLS"),+ use_ssl=get_instance_setting("EMAIL_USE_SSL"),+ # Bound the socket so a relay that goes silent mid-conversation raises TimeoutError+ # (retried below) instead of pinning the worker forever — the silent-hang case.+ timeout=get_instance_setting("EMAIL_TIMEOUT"),+ )+ connection.open()- with transaction.atomic():for dest in to:- record, _ = MessagingRecord.objects.get_or_create(raw_email=dest["raw_email"], campaign_key=campaign_key)+ # Per-recipient transaction so each delivery's `sent_at` commits before the next send.+ # A transient mid-batch failure re-raises into autoretry; the `if record.sent_at` guard+ # then skips the recipients already accepted on retry, instead of re-sending (and+ # duplicating) the whole batch.+ with transaction.atomic():+ record, _ = MessagingRecord.objects.get_or_create(+ raw_email=dest["raw_email"], campaign_key=campaign_key+ )+ record = MessagingRecord.objects.select_for_update().get(pk=record.pk)+ if record.sent_at:+ continue- record = MessagingRecord.objects.select_for_update().get(pk=record.pk)- if record.sent_at:- record.save()- continue-- records.append(record)- reply_to = reply_to or get_instance_setting("EMAIL_REPLY_TO")-- email_message = mail.EmailMultiAlternatives(- subject=subject,- body=txt_body,- from_email=get_instance_setting("EMAIL_DEFAULT_FROM"),- to=[dest["recipient"]],- headers=headers,- reply_to=[reply_to] if reply_to else None,- )+ effective_reply_to = reply_to or get_instance_setting("EMAIL_REPLY_TO")+ email_message = mail.EmailMultiAlternatives(+ subject=subject,+ body=txt_body,+ from_email=get_instance_setting("EMAIL_DEFAULT_FROM"),+ to=[dest["recipient"]],+ headers=headers,+ reply_to=[effective_reply_to] if effective_reply_to else None,+ )+ email_message.attach_alternative(html_body, "text/html")- email_message.attach_alternative(html_body, "text/html")- messages.append(email_message)-- connection = None- try:- klass = import_string(settings.EMAIL_BACKEND) if settings.EMAIL_BACKEND else EmailBackend- connection = klass(- host=get_instance_setting("EMAIL_HOST"),- port=get_instance_setting("EMAIL_PORT"),- username=get_instance_setting("EMAIL_HOST_USER"),- password=get_instance_setting("EMAIL_HOST_PASSWORD"),- use_tls=get_instance_setting("EMAIL_USE_TLS"),- use_ssl=get_instance_setting("EMAIL_USE_SSL"),- )- connection.open()- connection.send_messages(messages)+ connection.send_messages([email_message])- for record in records:record.sent_at = timezone.now()record.save()-- except Exception as err:- print("Could not send email:", err, file=sys.stderr)- capture_exception(err)- finally:+ EMAIL_SEND_COUNTER.labels(outcome="sent", transport="smtp").inc()+ except _TRANSIENT_SMTP_ERRORS as err:+ # Re-raise so the task's autoretry (3x + backoff) retries instead of dropping the email.+ # warning, not capture_exception: expected + auto-retried, capturing each attempt is noise.+ logger.warning("email_send_smtp_transient_error", error=str(err))+ EMAIL_SEND_COUNTER.labels(outcome="failed", transport="smtp").inc()+ raise+ except smtplib.SMTPRecipientsRefused as err:+ # Per-recipient codes live in .recipients ({addr: (code, msg)}), not a top-level smtp_code.+ # A 4xx (greylisting) is "try again later" → retry; 5xx (bad mailbox) is permanent.+ EMAIL_SEND_COUNTER.labels(outcome="failed", transport="smtp").inc()+ if any(400 <= code < 500 for code, _ in err.recipients.values()):+ logger.warning("email_send_smtp_transient_error", error=str(err))+ raise+ capture_exception(err)+ except smtplib.SMTPResponseException as err:+ # Send-path response codes (raised by sendmail): 4xx greylisting (450/451) and overloaded-relay+ # 421 are retryable; 5xx and auth (535) are permanent → swallow so we don't retry-storm the relay.+ EMAIL_SEND_COUNTER.labels(outcome="failed", transport="smtp").inc()+ if err.smtp_code is not None and 400 <= err.smtp_code < 500:+ logger.warning("email_send_smtp_transient_error", error=str(err))+ raise+ capture_exception(err)+ except Exception as err:+ capture_exception(err) # already logs the traceback via logger.exception+ EMAIL_SEND_COUNTER.labels(outcome="failed", transport="smtp").inc()+ finally:+ # Guard against a backend-construction failure (bad EMAIL_BACKEND, or TLS+SSL both set):+ # connection is still None there, and an unguarded None.close() would log a misleading+ # email_connection_close_failed over the real error already captured above.+ if connection is not None:try:- connection.close() # type: ignore+ connection.close()except Exception as err:- print(- "Could not close email connection (this can be ignored):",- err,- file=sys.stderr,- )+ logger.warning("email_connection_close_failed", error=str(err))# `utm_tags` carries hardcoded query-string fragments (`a=1&b=2`) and is neverdiff --git a/posthog/models/instance_setting.py b/posthog/models/instance_setting.pyindex 0d945b64e7a0..dd06f3cdd70b 100644--- a/posthog/models/instance_setting.py+++ b/posthog/models/instance_setting.py@@ -1,6 +1,7 @@import json+import timefrom contextlib import contextmanager-from functools import lru_cache+from threading import Lockfrom typing import Anyfrom django.db import models@@ -32,15 +33,37 @@ class InstanceSetting(models.Model):return parsed-@lru_cache+# Short TTL, not a permanent lru_cache: that pinned each value for a worker's life, so a+# DB-changed setting (e.g. a rotated SMTP password) never reached it without a restart.+_INSTANCE_SETTING_CACHE_TTL_SECONDS = 60+_instance_setting_cache: dict[str, tuple[float, Any]] = {}+_instance_setting_cache_lock = Lock()+++def _clear_instance_setting_cache() -> None:+ with _instance_setting_cache_lock:+ _instance_setting_cache.clear()++def get_instance_setting(key: str) -> Any:assert key in CONSTANCE_CONFIG, f"Unknown dynamic setting: {repr(key)}"+ with _instance_setting_cache_lock:+ cached = _instance_setting_cache.get(key)+ if cached is not None and time.monotonic() - cached[0] < _INSTANCE_SETTING_CACHE_TTL_SECONDS:+ return cached[1]++ # Fetch outside the lock so a slow query doesn't block other readers.saved_setting = InstanceSetting.objects.filter(key=CONSTANCE_DATABASE_PREFIX + key).first()- if saved_setting is not None:- return saved_setting.value- else:- return CONSTANCE_CONFIG[key][0] # Get the default value+ value = saved_setting.value if saved_setting is not None else CONSTANCE_CONFIG[key][0]++ with _instance_setting_cache_lock:+ _instance_setting_cache[key] = (time.monotonic(), value)+ return value+++# Preserve the lru_cache-era `.cache_clear()` interface that set_instance_setting and tests use.+get_instance_setting.cache_clear = _clear_instance_setting_cache # type: ignore[attr-defined]def get_instance_settings(keys: list[str]) -> Any:@@ -61,7 +84,7 @@ def set_instance_setting(key: str, value: Any):InstanceSetting.objects.update_or_create(key=CONSTANCE_DATABASE_PREFIX + key, defaults={"raw_value": json.dumps(value)})- get_instance_setting.cache_clear()+ get_instance_setting.cache_clear() # type: ignore[attr-defined]@contextmanagerdiff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.pyindex ec2ad5916a22..0042a65f53dd 100644--- a/posthog/settings/dynamic_settings.py+++ b/posthog/settings/dynamic_settings.py@@ -120,6 +120,12 @@ CONSTANCE_CONFIG = {"Reply address to which email clients should send responses.",str,),+ "EMAIL_TIMEOUT": (+ get_from_env("EMAIL_TIMEOUT", 30, type_cast=int),+ "Socket timeout in seconds for SMTP connections. Bounds how long a send waits on an "+ "unresponsive relay before raising (and being retried), instead of blocking forever.",+ int,+ ),"ASYNC_MIGRATIONS_OPT_OUT_EMAILS": (get_from_env("ASYNC_MIGRATIONS_OPT_OUT_EMAILS", False, type_cast=str_to_bool),"Used to disable emails from async migrations service",@@ -304,6 +310,7 @@ SETTINGS_ALLOWING_API_OVERRIDE = ("EMAIL_USE_SSL","EMAIL_DEFAULT_FROM","EMAIL_REPLY_TO",+ "EMAIL_TIMEOUT","ASYNC_MIGRATIONS_OPT_OUT_EMAILS","PERSON_ON_EVENTS_ENABLED","PERSON_ON_EVENTS_V2_ENABLED",diff --git a/posthog/test/base.py b/posthog/test/base.pyindex aa692116a5b3..3d174cbad224 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -682,7 +682,7 @@ class PostHogTestCase(SimpleTestCase):_setup_test_data(cls)def setUp(self):- get_instance_setting.cache_clear()+ get_instance_setting.cache_clear() # type: ignore[attr-defined]if get_instance_setting("PERSON_ON_EVENTS_ENABLED"):from posthog.models.team import utildiff --git a/posthog/test/test_email.py b/posthog/test/test_email.pyindex a285e6c2aeda..b20be26e1718 100644--- a/posthog/test/test_email.py+++ b/posthog/test/test_email.py@@ -1,4 +1,5 @@import hashlib+import smtplibimport datetimeimport dataclassesfrom decimal import Decimal@@ -16,7 +17,17 @@ from django.core.exceptions import ImproperlyConfiguredfrom django.test import override_settingsfrom django.utils import timezone-from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP, EmailMessage, _send_email, sanitize_email_properties+from parameterized import parameterized+from prometheus_client import REGISTRY++from posthog.email import (+ CUSTOMER_IO_TEMPLATE_ID_MAP,+ EmailMessage,+ _send_email,+ _send_via_http,+ _send_via_smtp,+ sanitize_email_properties,+)from posthog.models import Organization, Person, Team, Userfrom posthog.models.instance_setting import override_instance_configfrom posthog.models.messaging import MessagingRecord, get_email_hash, get_email_hashes@@ -97,6 +108,158 @@ class TestEmail(BaseTest):in message.html_body)+ def test_smtp_send_increments_sent_metric(self) -> None:+ # The charts alert reads posthog_email_send_total{outcome,transport}; this locks the+ # name + label contract so a removed/mislabelled increment can't silently blind it.+ labels = {"outcome": "sent", "transport": "smtp"}+ before = REGISTRY.get_sample_value("posthog_email_send_total", labels) or 0.0++ with override_instance_config("EMAIL_HOST", "localhost"):+ message = EmailMessage(+ campaign_key="metric_test_campaign", subject="Subject", template_name="async_migration_error"+ )+ message.add_recipient("[email protected]")+ message.send(send_async=False)++ self.assertEqual(len(mail.outbox), 1)+ after = REGISTRY.get_sample_value("posthog_email_send_total", labels) or 0.0+ self.assertEqual(after - before, 1.0)++ @parameterized.expand(+ [+ ("transient_disconnect", smtplib.SMTPServerDisconnected("dropped"), True),+ ("transient_oserror", ConnectionResetError("reset"), True),+ ("transient_timeout", TimeoutError("hung relay"), True),+ # Send-path 4xx ("try again later") must re-raise so autoretry fires, not be swallowed.+ ("transient_data_greylist", smtplib.SMTPDataError(451, b"greylisted, try later"), True),+ ("transient_sender_421", smtplib.SMTPSenderRefused(421, b"service unavailable", "[email protected]"), True),+ (+ "transient_recipients_greylist",+ smtplib.SMTPRecipientsRefused({"[email protected]": (450, b"greylisted")}),+ True,+ ),+ ("permanent_auth", smtplib.SMTPAuthenticationError(535, b"bad creds"), False),+ ("permanent_data_5xx", smtplib.SMTPDataError(554, b"transaction failed"), False),+ ("permanent_recipients", smtplib.SMTPRecipientsRefused({}), False),+ (+ "permanent_recipients_5xx",+ smtplib.SMTPRecipientsRefused({"[email protected]": (550, b"no such user")}),+ False,+ ),+ ]+ )+ def test_smtp_error_retry_classification(self, name, exc, should_reraise) -> None:+ # Transient errors (connection drops + send-path 4xx greylisting/421) re-raise so autoretry+ # fires; auth/5xx/permanent stay swallowed (no retry-storm of the relay's per-IP limit).+ # Both record one failed metric.+ failed_labels = {"outcome": "failed", "transport": "smtp"}+ before = REGISTRY.get_sample_value("posthog_email_send_total", failed_labels) or 0.0++ with (+ override_instance_config("EMAIL_HOST", "localhost"),+ patch("django.core.mail.backends.locmem.EmailBackend.send_messages", side_effect=exc),+ ):+ kwargs: dict[str, Any] = {+ "to": [{"raw_email": f"{name}@posthog.com", "recipient": f"{name}@posthog.com"}],+ "campaign_key": f"retry_{name}",+ "subject": "Subject",+ "txt_body": "",+ "html_body": "<p>hi</p>",+ "headers": {},+ }+ if should_reraise:+ with self.assertRaises(type(exc)):+ _send_via_smtp(**kwargs)+ else:+ _send_via_smtp(**kwargs)++ after = REGISTRY.get_sample_value("posthog_email_send_total", failed_labels) or 0.0+ self.assertEqual(after - before, 1.0)++ def test_smtp_transient_failure_preserves_already_sent_recipients(self) -> None:+ # A transient failure on a later recipient must not roll back the recipients already+ # accepted by the relay — otherwise the task's autoretry re-sends the whole batch and+ # duplicates the already-delivered emails. Each delivery commits its own `sent_at`.+ with (+ override_instance_config("EMAIL_HOST", "localhost"),+ patch(+ "django.core.mail.backends.locmem.EmailBackend.send_messages",+ side_effect=[1, smtplib.SMTPServerDisconnected("dropped mid-batch")],+ ),+ ):+ kwargs: dict[str, Any] = {+ "to": [+ {"raw_email": "[email protected]", "recipient": "[email protected]"},+ {"raw_email": "[email protected]", "recipient": "[email protected]"},+ ],+ "campaign_key": "batch_transient",+ "subject": "Subject",+ "txt_body": "",+ "html_body": "<p>hi</p>",+ "headers": {},+ }+ with self.assertRaises(smtplib.SMTPServerDisconnected):+ _send_via_smtp(**kwargs)++ first = MessagingRecord.objects.filter(+ email_hash__in=get_email_hashes("[email protected]"), campaign_key="batch_transient"+ ).first()+ self.assertIsNotNone(first)+ self.assertIsNotNone(first.sent_at) # committed before the failure → a retry skips it+ second = MessagingRecord.objects.filter(+ email_hash__in=get_email_hashes("[email protected]"), campaign_key="batch_transient"+ ).first()+ self.assertIsNone(second) # its transaction rolled back → retried fresh, no half-written row++ def test_smtp_connection_built_with_bounded_timeout(self) -> None:+ # Without a socket timeout a silently-hung relay pins the worker forever and the new+ # TimeoutError retry branch can never fire — so the backend must get a bounded timeout.+ mock_backend_cls = MagicMock()+ with (+ override_instance_config("EMAIL_HOST", "localhost"),+ override_instance_config("EMAIL_TIMEOUT", 17),+ patch("posthog.email.import_string", return_value=mock_backend_cls),+ self.settings(EMAIL_BACKEND="some.smtp.Backend"),+ ):+ _send_via_smtp(+ to=[{"raw_email": "[email protected]", "recipient": "[email protected]"}],+ campaign_key="timeout_kwarg",+ subject="Subject",+ txt_body="",+ html_body="<p>hi</p>",+ headers={},+ )++ self.assertEqual(mock_backend_cls.call_args.kwargs.get("timeout"), 17)++ @patch("posthog.email.requests.post")+ def test_send_via_http_failed_metric_counts_undelivered_recipients(self, mock_post) -> None:+ # `failed` must count every recipient that didn't get through (the failing one + any not yet+ # attempted), per recipient like `sent` — not once per batch — or the alertable failure rate+ # under-reports multi-recipient batches.+ ok = MagicMock(status_code=200)+ ok.json.return_value = {}+ bad = MagicMock(status_code=500, text="boom")+ mock_post.side_effect = [ok, bad]++ failed_labels = {"outcome": "failed", "transport": "http"}+ before = REGISTRY.get_sample_value("posthog_email_send_total", failed_labels) or 0.0++ with override_instance_config("EMAIL_HOST", "localhost"), self.settings(CUSTOMER_IO_API_KEY="test-key"):+ _send_via_http(+ to=[+ {"raw_email": "[email protected]"},+ {"raw_email": "[email protected]"},+ {"raw_email": "[email protected]"},+ ],+ campaign_key="http_failcount",+ template_name="2fa_enabled",+ properties={},+ )++ after = REGISTRY.get_sample_value("posthog_email_send_total", failed_labels) or 0.0+ self.assertEqual(after - before, 2.0) # b failed + c never attempted; a succeeded+@patch("posthoganalytics.capture")@patch("posthog.email.requests.post")def test_send_via_http_success(self, mock_post, mock_capture) -> None:diff --git a/posthog/test/test_instance_setting_model.py b/posthog/test/test_instance_setting_model.pyindex 46a13b8d3456..04e541e4a2bc 100644--- a/posthog/test/test_instance_setting_model.py+++ b/posthog/test/test_instance_setting_model.py@@ -4,6 +4,7 @@ import pytestfrom posthog.models.instance_setting import (InstanceSetting,+ _clear_instance_setting_cache,get_instance_setting,get_instance_settings,override_instance_config,@@ -11,6 +12,13 @@ from posthog.models.instance_setting import ()[email protected](autouse=True)+def _reset_instance_setting_cache():+ _clear_instance_setting_cache()+ yield+ _clear_instance_setting_cache()++def test_unknown_key_raises(db):with pytest.raises(AssertionError):get_instance_setting("UNKNOWN_SETTING")@@ -138,3 +146,15 @@ def test_admin_save_model_wraps_bare_strings(db):admin.save_model(request, obj4, form=None, change=False)assert obj4.raw_value == "42"assert obj4.value == 42+++def test_db_change_propagates_after_ttl(db, monkeypatch):+ # A direct DB change (no cache_clear) stays stale while cached, then propagates once the TTL+ # elapses — guards against reverting to a permanent cache (the stale-credential bug).+ initial = get_instance_setting("EMAIL_HOST")++ InstanceSetting.objects.create(key="constance:posthog:EMAIL_HOST", raw_value='"smtp.changed.test"')+ assert get_instance_setting("EMAIL_HOST") == initial++ monkeypatch.setattr("posthog.models.instance_setting._INSTANCE_SETTING_CACHE_TTL_SECONDS", 0)+ assert get_instance_setting("EMAIL_HOST") == "smtp.changed.test"