From c79aabfbbafc96cbeddec70bb74df7ce915cf226 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:33:11 +0000 Subject: [PATCH 1/5] feat(emails): let a code send turn off open and click tracking Adds track_opens_and_clicks to the code form of emails.send. False sends the email without PostHog's open pixel and rewritten links. The field goes into the request body only when the caller sets it, so a default send keeps today's body. The template form refuses it, like capture_engagement. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/check_strict_types.sh | 3 ++- .../emails-track-opens-and-clicks.md | 17 +++++++++++++++ posthog/emails.py | 14 +++++++++++++ posthog/test/test_emails.py | 21 +++++++++++++++++++ references/public_api_snapshot.txt | 1 + 5 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 .sampo/changesets/emails-track-opens-and-clicks.md diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh index 4e41c9e8f..eb907bfa8 100755 --- a/.github/scripts/check_strict_types.sh +++ b/.github/scripts/check_strict_types.sh @@ -43,7 +43,7 @@ _ = (flag_value, all_flags, enabled, payload, evaluations, active) emails = Emails("phs_example") template_send: SendEmailResult = emails.send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", template_data={"name": "Ada"}) -rendered_send: SendEmailResult = emails.send(to="user@example.com", template_key="password-reset", subject="Reset", html="

Reset

", from_="Acme ", reply_to=["help@example.com"], capture_engagement=False, max_retries=0) +rendered_send: SendEmailResult = emails.send(to="user@example.com", template_key="password-reset", subject="Reset", html="

Reset

", from_="Acme ", reply_to=["help@example.com"], capture_engagement=False, track_opens_and_clicks=False, max_retries=0) _ = (template_send, rendered_send) @@ -89,6 +89,7 @@ Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3 Emails("phs_example").send(to="user@example.com", template_key="welcome", html="

Hi

") # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", cc="team@example.com") # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", capture_engagement=False) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", track_opens_and_clicks=False) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", template_data={"name": "Ada"}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", cc="team@example.com") # expected-type-error diff --git a/.sampo/changesets/emails-track-opens-and-clicks.md b/.sampo/changesets/emails-track-opens-and-clicks.md new file mode 100644 index 000000000..3c1392102 --- /dev/null +++ b/.sampo/changesets/emails-track-opens-and-clicks.md @@ -0,0 +1,17 @@ +--- +pypi/posthog: minor +--- + +A send with your own content now takes `track_opens_and_clicks`. It defaults to `True`. With `track_opens_and_clicks=False`, the email goes out without PostHog's open pixel and without links rewritten to count clicks, so PostHog can't count its opens and clicks. It is independent of `capture_engagement`, which decides whether engagement events are captured on the recipient's person. The template form doesn't take it. + +```python +posthog.emails.send( + to="user@example.com", + template_key="welcome", + subject="Welcome to Acme", + html=rendered_html, + track_opens_and_clicks=False, +) +``` + +The field needs PostHog's API support, which is rolling out. A send that leaves it out sends the same request as before. diff --git a/posthog/emails.py b/posthog/emails.py index c53528c7c..12c69f76d 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -247,6 +247,13 @@ class CodeEmailArgs(_RecipientArgs): engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. + track_opens_and_clicks: Whether the email carries open and click + tracking: PostHog's open pixel and links rewritten to count + clicks. Defaults to ``True``. With ``False``, the email goes out + without either, so PostHog can't count its opens and clicks. + Independent of ``capture_engagement``, which decides whether + engagement events are captured on the recipient's person. The + template form doesn't take it. distinct_id: The recipient's distinct ID in your product. idempotency_key: 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for @@ -264,6 +271,7 @@ class CodeEmailArgs(_RecipientArgs): from_: NotRequired[Optional[str]] reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] capture_engagement: NotRequired[Optional[bool]] + track_opens_and_clicks: NotRequired[Optional[bool]] _OPTIONAL_CODE_FIELDS = frozenset( @@ -273,6 +281,7 @@ class CodeEmailArgs(_RecipientArgs): "from_", "reply_to", "capture_engagement", + "track_opens_and_clicks", } ) @@ -385,6 +394,11 @@ def _sender(args: Mapping[str, Any]) -> dict[str, Any]: if not isinstance(capture_engagement, bool): raise TypeError("capture_engagement must be True or False.") sender["capture_engagement"] = capture_engagement + if "track_opens_and_clicks" in args: + track_opens_and_clicks = args["track_opens_and_clicks"] + if not isinstance(track_opens_and_clicks, bool): + raise TypeError("track_opens_and_clicks must be True or False.") + sender["track_opens_and_clicks"] = track_opens_and_clicks return sender diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index eaf1c0949..9f2a4b383 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -656,6 +656,16 @@ def send_code(emails: Emails, **overrides: Any): "distinct_id": "user_123", }, ), + ( + "untracked", + {"html": HTML, "track_opens_and_clicks": False}, + {"html": HTML, "track_opens_and_clicks": False}, + ), + ( + "tracked", + {"html": HTML, "track_opens_and_clicks": True}, + {"html": HTML, "track_opens_and_clicks": True}, + ), ( "several_reply_to", {"html": HTML, "reply_to": ["a@example.com", "b@example.com"]}, @@ -674,6 +684,7 @@ def send_code(emails: Emails, **overrides: Any): "from_": None, "reply_to": None, "capture_engagement": None, + "track_opens_and_clicks": None, "distinct_id": None, }, {"html": HTML}, @@ -782,6 +793,16 @@ def handler(request: httpx.Request) -> httpx.Response: }, TypeError, ), + ( + "track_opens_and_clicks_on_template_form", + { + "template_id": TEMPLATE_ID, + "template_key": None, + "subject": None, + "track_opens_and_clicks": False, + }, + TypeError, + ), ] ) def test_rejects_a_code_send_that_mixes_or_misses_fields(_name, overrides, error): diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index bfffd5d64..3ca80f440 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -895,6 +895,7 @@ attribute posthog.emails.CodeEmailArgs.reply_to: NotRequired[Optional[Union[str, attribute posthog.emails.CodeEmailArgs.subject: str attribute posthog.emails.CodeEmailArgs.template_key: str attribute posthog.emails.CodeEmailArgs.text: NotRequired[Optional[str]] +attribute posthog.emails.CodeEmailArgs.track_opens_and_clicks: NotRequired[Optional[bool]] attribute posthog.emails.EmailError.code = code attribute posthog.emails.EmailError.docs_url = docs_url attribute posthog.emails.EmailError.field = field From 28fd4e575f863e681d7aa9223e73a7e7adec50ce Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:06:05 +0000 Subject: [PATCH 2/5] docs(emails): say track_opens_and_clicks only removes the open pixel PostHog never rewrites the links of an email sent from code, so it counts no clicks either way. False removes the open pixel only. Co-Authored-By: Claude Opus 5.5 --- .../changesets/emails-track-opens-and-clicks.md | 2 +- posthog/emails.py | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/.sampo/changesets/emails-track-opens-and-clicks.md b/.sampo/changesets/emails-track-opens-and-clicks.md index 3c1392102..d5725825b 100644 --- a/.sampo/changesets/emails-track-opens-and-clicks.md +++ b/.sampo/changesets/emails-track-opens-and-clicks.md @@ -2,7 +2,7 @@ pypi/posthog: minor --- -A send with your own content now takes `track_opens_and_clicks`. It defaults to `True`. With `track_opens_and_clicks=False`, the email goes out without PostHog's open pixel and without links rewritten to count clicks, so PostHog can't count its opens and clicks. It is independent of `capture_engagement`, which decides whether engagement events are captured on the recipient's person. The template form doesn't take it. +A send with your own content now takes `track_opens_and_clicks`. It defaults to `True`. With `track_opens_and_clicks=False`, the email goes out without PostHog's open pixel, so PostHog can't count its opens. PostHog doesn't track clicks on emails sent from code, so their links are never rewritten either way. It is independent of `capture_engagement`, which decides whether engagement events are captured on the recipient's person. The template form doesn't take it. ```python posthog.emails.send( diff --git a/posthog/emails.py b/posthog/emails.py index 12c69f76d..15a63ff9b 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -247,13 +247,14 @@ class CodeEmailArgs(_RecipientArgs): engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. - track_opens_and_clicks: Whether the email carries open and click - tracking: PostHog's open pixel and links rewritten to count - clicks. Defaults to ``True``. With ``False``, the email goes out - without either, so PostHog can't count its opens and clicks. - Independent of ``capture_engagement``, which decides whether - engagement events are captured on the recipient's person. The - template form doesn't take it. + track_opens_and_clicks: Whether PostHog tracks opens and clicks of + the email. Defaults to ``True``. With ``False``, the email goes + out without PostHog's open pixel, so PostHog can't count its + opens. PostHog doesn't track clicks on emails sent from code, so + their links are never rewritten either way. Independent of + ``capture_engagement``, which decides whether engagement events + are captured on the recipient's person. The template form + doesn't take it. distinct_id: The recipient's distinct ID in your product. idempotency_key: 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for From b3416dc2cd606d39a90870f231d75f0ccf884b60 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:10:43 +0000 Subject: [PATCH 3/5] feat(emails): let a code send choose its tracking Replace track_opens_and_clicks with tracking: True, False, or an EmailTracking dict of opens, clicks and engagement. Leave tracking and capture_engagement out of the body unless the caller sets them, so the API can refuse a send that sets both. Deprecate capture_engagement. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/check_strict_types.sh | 9 +- .../emails-track-opens-and-clicks.md | 17 ---- .sampo/changesets/emails-tracking.md | 21 +++++ posthog/emails.py | 83 ++++++++++++++----- posthog/test/test_emails.py | 31 ++++--- references/public_api_snapshot.txt | 6 +- 6 files changed, 113 insertions(+), 54 deletions(-) delete mode 100644 .sampo/changesets/emails-track-opens-and-clicks.md create mode 100644 .sampo/changesets/emails-tracking.md diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh index eb907bfa8..04cd7a363 100755 --- a/.github/scripts/check_strict_types.sh +++ b/.github/scripts/check_strict_types.sh @@ -43,8 +43,10 @@ _ = (flag_value, all_flags, enabled, payload, evaluations, active) emails = Emails("phs_example") template_send: SendEmailResult = emails.send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", template_data={"name": "Ada"}) -rendered_send: SendEmailResult = emails.send(to="user@example.com", template_key="password-reset", subject="Reset", html="

Reset

", from_="Acme ", reply_to=["help@example.com"], capture_engagement=False, track_opens_and_clicks=False, max_retries=0) -_ = (template_send, rendered_send) +rendered_send: SendEmailResult = emails.send(to="user@example.com", template_key="password-reset", subject="Reset", html="

Reset

", from_="Acme ", reply_to=["help@example.com"], capture_engagement=False, max_retries=0) +tracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="

Hi

", tracking={"clicks": True, "engagement": False}) +untracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="

Hi

", tracking=False) +_ = (template_send, rendered_send, tracked_send, untracked_send) async def async_email_types() -> None: @@ -89,7 +91,8 @@ Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3 Emails("phs_example").send(to="user@example.com", template_key="welcome", html="

Hi

") # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", cc="team@example.com") # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", capture_engagement=False) # expected-type-error -Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", track_opens_and_clicks=False) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", tracking=False) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", tracking={"open": False}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", template_data={"name": "Ada"}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", cc="team@example.com") # expected-type-error diff --git a/.sampo/changesets/emails-track-opens-and-clicks.md b/.sampo/changesets/emails-track-opens-and-clicks.md deleted file mode 100644 index d5725825b..000000000 --- a/.sampo/changesets/emails-track-opens-and-clicks.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -pypi/posthog: minor ---- - -A send with your own content now takes `track_opens_and_clicks`. It defaults to `True`. With `track_opens_and_clicks=False`, the email goes out without PostHog's open pixel, so PostHog can't count its opens. PostHog doesn't track clicks on emails sent from code, so their links are never rewritten either way. It is independent of `capture_engagement`, which decides whether engagement events are captured on the recipient's person. The template form doesn't take it. - -```python -posthog.emails.send( - to="user@example.com", - template_key="welcome", - subject="Welcome to Acme", - html=rendered_html, - track_opens_and_clicks=False, -) -``` - -The field needs PostHog's API support, which is rolling out. A send that leaves it out sends the same request as before. diff --git a/.sampo/changesets/emails-tracking.md b/.sampo/changesets/emails-tracking.md new file mode 100644 index 000000000..c3f0a6484 --- /dev/null +++ b/.sampo/changesets/emails-tracking.md @@ -0,0 +1,21 @@ +--- +pypi/posthog: minor +--- + +A send with `template_key` now takes `tracking`, which chooses what PostHog tracks for the email. Without it, PostHog counts opens, leaves the links as they are, and captures engagement events. `tracking=True` turns on opens, clicks and engagement events. `tracking=False` turns them all off. A dict such as `{"clicks": True}` or `{"engagement": False}` turns each kind on or off, and a key you leave out keeps its default. The template form doesn't take it. + +```python +posthog.emails.send( + to="user@example.com", + template_key="newsletter", + subject="What's new at Acme", + html=rendered_html, + tracking={"clicks": True}, +) +``` + +Clicks are off by default because PostHog can't tell whether a link carries a login or password reset token. Turn them on only when the email's links are safe to send through PostHog's click tracking. + +`capture_engagement` is deprecated in favor of `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both. + +`tracking` needs PostHog's API support, which is rolling out. Until it reaches your PostHog instance, PostHog refuses a send that sets it. A send without it works as before. diff --git a/posthog/emails.py b/posthog/emails.py index 15a63ff9b..0c92f1899 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -131,6 +131,7 @@ "CodeEmailArgs", "EmailError", "EmailStatus", + "EmailTracking", "EmailWarning", "Emails", "SendEmailResult", @@ -223,6 +224,27 @@ class TemplateEmailArgs(_RecipientArgs): template_data: NotRequired[Optional[Mapping[str, Any]]] +class EmailTracking(TypedDict, total=False): + """Which kinds of tracking a send with ``template_key`` turns on. + + A key you leave out keeps its default. + + Args: + opens: Counts opens with PostHog's open pixel. Defaults to ``True``. + clicks: Counts clicks by sending the email's links through PostHog's + click tracking. Defaults to ``False``. Needs ``opens``: PostHog + refuses a send with ``opens=False`` and ``clicks=True``. + engagement: Captures the email's engagement events (sent, + delivered, opened, clicked, bounced) as events of the recipient. + Defaults to ``True``. A project whose admin turned engagement + capture off captures nothing, whatever the send asks. + """ + + opens: bool + clicks: bool + engagement: bool + + class CodeEmailArgs(_RecipientArgs): """A send of email content that your code rendered for one recipient, named by a key. @@ -242,19 +264,26 @@ class CodeEmailArgs(_RecipientArgs): without a plain-text part. from_: A verified sender, such as ``"Acme "``. reply_to: One address or a list of addresses. An empty list sends no reply-to. - capture_engagement: Capture the email's opens and clicks as events of - the recipient. Defaults to ``True``. A project whose admin turned - engagement capture off captures nothing, whatever the send asks. A - template made in PostHog follows the project's setting, so the - template form doesn't take it. - track_opens_and_clicks: Whether PostHog tracks opens and clicks of - the email. Defaults to ``True``. With ``False``, the email goes - out without PostHog's open pixel, so PostHog can't count its - opens. PostHog doesn't track clicks on emails sent from code, so - their links are never rewritten either way. Independent of - ``capture_engagement``, which decides whether engagement events - are captured on the recipient's person. The template form + capture_engagement: Deprecated, use ``tracking={"engagement": False}``. + It keeps working, but PostHog refuses a send that sets both + ``capture_engagement`` and ``tracking``. Captures the email's + engagement events as events of the recipient. Defaults to + ``True``. A project whose admin turned engagement capture off + captures nothing, whatever the send asks. A template made in + PostHog follows the project's setting, so the template form doesn't take it. + tracking: What PostHog tracks for this email. Without it, PostHog + counts opens with its open pixel, leaves the links as they are, + and captures engagement events. ``True`` turns on opens, clicks + and engagement events. ``False`` turns off all tracking, + including kinds PostHog adds later: PostHog can't count the + email's opens or clicks, and captures no engagement events. An + :class:`EmailTracking` dict turns each kind on or off, and a key + you leave out keeps its default. Clicks are off by default + because PostHog can't tell whether a link carries a login or + password reset token. Turn them on only when the email's links + are safe to send through PostHog's click tracking. The template + form doesn't take it. distinct_id: The recipient's distinct ID in your product. idempotency_key: 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for @@ -272,7 +301,7 @@ class CodeEmailArgs(_RecipientArgs): from_: NotRequired[Optional[str]] reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] capture_engagement: NotRequired[Optional[bool]] - track_opens_and_clicks: NotRequired[Optional[bool]] + tracking: NotRequired[Optional[Union[bool, EmailTracking]]] _OPTIONAL_CODE_FIELDS = frozenset( @@ -282,7 +311,7 @@ class CodeEmailArgs(_RecipientArgs): "from_", "reply_to", "capture_engagement", - "track_opens_and_clicks", + "tracking", } ) @@ -391,18 +420,26 @@ def _sender(args: Mapping[str, Any]) -> dict[str, Any]: reply_to = _addresses("reply_to", args["reply_to"]) if "reply_to" in args else [] if reply_to: sender["reply_to"] = reply_to - capture_engagement = args.get("capture_engagement", True) - if not isinstance(capture_engagement, bool): - raise TypeError("capture_engagement must be True or False.") - sender["capture_engagement"] = capture_engagement - if "track_opens_and_clicks" in args: - track_opens_and_clicks = args["track_opens_and_clicks"] - if not isinstance(track_opens_and_clicks, bool): - raise TypeError("track_opens_and_clicks must be True or False.") - sender["track_opens_and_clicks"] = track_opens_and_clicks + if "capture_engagement" in args: + capture_engagement = args["capture_engagement"] + if not isinstance(capture_engagement, bool): + raise TypeError("capture_engagement must be True or False.") + sender["capture_engagement"] = capture_engagement + if "tracking" in args: + sender["tracking"] = _tracking(args["tracking"]) return sender +def _tracking(value: Any) -> Union[bool, dict[str, Any]]: + if isinstance(value, bool): + return value + if isinstance(value, Mapping): + return dict(value) + raise TypeError( + "tracking must be True, False or a dict of opens, clicks and engagement." + ) + + def _addresses(field: str, value: Any) -> list[str]: addresses = [value] if isinstance(value, str) else value if not isinstance(addresses, Sequence) or not all( diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index 9f2a4b383..86a1573fc 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -657,14 +657,25 @@ def send_code(emails: Emails, **overrides: Any): }, ), ( - "untracked", - {"html": HTML, "track_opens_and_clicks": False}, - {"html": HTML, "track_opens_and_clicks": False}, + "all_tracking_off", + {"html": HTML, "tracking": False}, + {"html": HTML, "tracking": False}, ), ( - "tracked", - {"html": HTML, "track_opens_and_clicks": True}, - {"html": HTML, "track_opens_and_clicks": True}, + "all_tracking_on", + {"html": HTML, "tracking": True}, + {"html": HTML, "tracking": True}, + ), + ( + "each_kind_of_tracking_chosen", + { + "html": HTML, + "tracking": {"opens": True, "clicks": True, "engagement": False}, + }, + { + "html": HTML, + "tracking": {"opens": True, "clicks": True, "engagement": False}, + }, ), ( "several_reply_to", @@ -684,7 +695,7 @@ def send_code(emails: Emails, **overrides: Any): "from_": None, "reply_to": None, "capture_engagement": None, - "track_opens_and_clicks": None, + "tracking": None, "distinct_id": None, }, {"html": HTML}, @@ -704,7 +715,6 @@ def test_rendered_content_is_posted_as_is(_name, overrides, extra_body): "to": "user@example.com", "template_key": "password-reset", "subject": "Reset your password", - "capture_engagement": True, **extra_body, } @@ -794,15 +804,16 @@ def handler(request: httpx.Request) -> httpx.Response: TypeError, ), ( - "track_opens_and_clicks_on_template_form", + "tracking_on_template_form", { "template_id": TEMPLATE_ID, "template_key": None, "subject": None, - "track_opens_and_clicks": False, + "tracking": False, }, TypeError, ), + ("tracking_not_bool_or_dict", {"html": HTML, "tracking": "off"}, TypeError), ] ) def test_rejects_a_code_send_that_mixes_or_misses_fields(_name, overrides, error): diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 3ca80f440..c9db76c04 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -895,7 +895,7 @@ attribute posthog.emails.CodeEmailArgs.reply_to: NotRequired[Optional[Union[str, attribute posthog.emails.CodeEmailArgs.subject: str attribute posthog.emails.CodeEmailArgs.template_key: str attribute posthog.emails.CodeEmailArgs.text: NotRequired[Optional[str]] -attribute posthog.emails.CodeEmailArgs.track_opens_and_clicks: NotRequired[Optional[bool]] +attribute posthog.emails.CodeEmailArgs.tracking: NotRequired[Optional[Union[bool, EmailTracking]]] attribute posthog.emails.EmailError.code = code attribute posthog.emails.EmailError.docs_url = docs_url attribute posthog.emails.EmailError.field = field @@ -910,6 +910,9 @@ attribute posthog.emails.EmailStatus.id: str attribute posthog.emails.EmailStatus.reason: Optional[str] = None attribute posthog.emails.EmailStatus.status: str attribute posthog.emails.EmailStatus.status_at: datetime +attribute posthog.emails.EmailTracking.clicks: bool +attribute posthog.emails.EmailTracking.engagement: bool +attribute posthog.emails.EmailTracking.opens: bool attribute posthog.emails.EmailWarning.code: str attribute posthog.emails.EmailWarning.fix: Optional[str] = None attribute posthog.emails.EmailWarning.message: str @@ -1347,6 +1350,7 @@ class posthog.emails.AsyncEmails(secret_key: Optional[str], *, host: Optional[st class posthog.emails.CodeEmailArgs class posthog.emails.EmailError(*, name: str, code: str, message: str, status_code: Optional[int] = None, why: Optional[str] = None, fix: Optional[str] = None, docs_url: Optional[str] = None, field: Optional[str] = None, retry_after: Optional[float] = None) class posthog.emails.EmailStatus(id: str, status: str, created_at: datetime, status_at: datetime, reason: Optional[str] = None) +class posthog.emails.EmailTracking class posthog.emails.EmailWarning(code: str, message: str, fix: Optional[str] = None) class posthog.emails.Emails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, session: Optional[requests.Session] = None, migrated_from: Optional[str] = None) class posthog.emails.SendEmailResult(id: str, replayed: bool = False, warnings: tuple[EmailWarning, ...] = ()) From 5d3f2d0048f7cce6e6626ddb13f0a4a7f6b606ac Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:23:51 +0000 Subject: [PATCH 4/5] test(emails): prove the tracking choice over real HTTP Send each tracking form through the public send API to a local HTTP server and assert the body it receives, instead of a stubbed transport. Co-Authored-By: Claude Opus 5.5 --- posthog/test/test_emails.py | 98 ++++++++++++++++++++++++++++--------- 1 file changed, 75 insertions(+), 23 deletions(-) diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index 86a1573fc..81a78ee79 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -3,9 +3,11 @@ import asyncio import json import logging +import threading from datetime import datetime, timezone from decimal import Decimal -from typing import Any, Optional, Union +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import Any, Iterator, Optional, Union from unittest import mock import httpx @@ -656,27 +658,6 @@ def send_code(emails: Emails, **overrides: Any): "distinct_id": "user_123", }, ), - ( - "all_tracking_off", - {"html": HTML, "tracking": False}, - {"html": HTML, "tracking": False}, - ), - ( - "all_tracking_on", - {"html": HTML, "tracking": True}, - {"html": HTML, "tracking": True}, - ), - ( - "each_kind_of_tracking_chosen", - { - "html": HTML, - "tracking": {"opens": True, "clicks": True, "engagement": False}, - }, - { - "html": HTML, - "tracking": {"opens": True, "clicks": True, "engagement": False}, - }, - ), ( "several_reply_to", {"html": HTML, "reply_to": ["a@example.com", "b@example.com"]}, @@ -695,7 +676,6 @@ def send_code(emails: Emails, **overrides: Any): "from_": None, "reply_to": None, "capture_engagement": None, - "tracking": None, "distinct_id": None, }, {"html": HTML}, @@ -719,6 +699,78 @@ def test_rendered_content_is_posted_as_is(_name, overrides, extra_body): } +class _CaptureServer(HTTPServer): + received: list[Any] + + +class _CaptureHandler(BaseHTTPRequestHandler): + server: _CaptureServer + + def do_POST(self) -> None: + body = self.rfile.read(int(self.headers["Content-Length"])) + self.server.received.append(json.loads(body)) + reply = json.dumps({"message_id": "msg_1", "replayed": False}).encode() + self.send_response(202) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(reply))) + self.end_headers() + self.wfile.write(reply) + + def log_message(self, *args: Any) -> None: + pass + + +@pytest.fixture +def capture_server() -> Iterator[_CaptureServer]: + server = _CaptureServer(("127.0.0.1", 0), _CaptureHandler) + server.received = [] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield server + server.shutdown() + server.server_close() + + +@pytest.mark.parametrize( + "overrides, extra_body", + [ + pytest.param({}, {}, id="no_tracking_choice"), + pytest.param( + {"tracking": None, "capture_engagement": None}, {}, id="none_as_left_out" + ), + pytest.param({"tracking": False}, {"tracking": False}, id="all_tracking_off"), + pytest.param({"tracking": True}, {"tracking": True}, id="all_tracking_on"), + pytest.param( + {"tracking": {"opens": True, "clicks": True, "engagement": False}}, + {"tracking": {"opens": True, "clicks": True, "engagement": False}}, + id="each_kind_of_tracking_chosen", + ), + pytest.param( + {"capture_engagement": False}, + {"capture_engagement": False}, + id="deprecated_capture_engagement", + ), + ], +) +def test_a_code_send_delivers_its_tracking_choice( + capture_server, overrides, extra_body +): + host = f"http://127.0.0.1:{capture_server.server_port}" + with Emails(SECRET_KEY, host=host) as emails: + result = send_code(emails, html=HTML, **overrides) + + assert result.id == "msg_1" + assert capture_server.received == [ + { + "to": "user@example.com", + "template_key": "password-reset", + "subject": "Reset your password", + "html": HTML, + **extra_body, + } + ] + + @pytest.mark.asyncio async def test_async_client_posts_rendered_content_and_names_the_provider(): seen: list[httpx.Request] = [] From 9ae08ac6511971cbbbdd34e0832146bc5da08158 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Wed, 11 Nov 2026 04:08:24 +0000 Subject: [PATCH 5/5] feat(emails): let a code send mark its email sensitive A code send now takes an optional `sensitive`, sent only when set. Without it, PostHog keeps today's behavior: a send whose template_key matches a saved template follows that template, and any other send is sensitive. Click tracking follows it unless `tracking` sets clicks. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/check_strict_types.sh | 2 ++ .sampo/changesets/emails-tracking.md | 12 +++++--- posthog/emails.py | 44 ++++++++++++++++----------- posthog/test/test_emails.py | 23 ++++++++++++-- references/public_api_snapshot.txt | 1 + 5 files changed, 56 insertions(+), 26 deletions(-) diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh index 04cd7a363..afa3c483d 100755 --- a/.github/scripts/check_strict_types.sh +++ b/.github/scripts/check_strict_types.sh @@ -46,6 +46,7 @@ template_send: SendEmailResult = emails.send(to="user@example.com", template_id= rendered_send: SendEmailResult = emails.send(to="user@example.com", template_key="password-reset", subject="Reset", html="

Reset

", from_="Acme ", reply_to=["help@example.com"], capture_engagement=False, max_retries=0) tracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="

Hi

", tracking={"clicks": True, "engagement": False}) untracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="

Hi

", tracking=False) +not_sensitive_send: SendEmailResult = emails.send(to="user@example.com", template_key="newsletter", subject="News", html="

News

", sensitive=False) _ = (template_send, rendered_send, tracked_send, untracked_send) @@ -92,6 +93,7 @@ Emails("phs_example").send(to="user@example.com", template_key="welcome", html=" Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", cc="team@example.com") # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", capture_engagement=False) # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", tracking=False) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", sensitive=False) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", tracking={"open": False}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", template_data={"name": "Ada"}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", cc="team@example.com") # expected-type-error diff --git a/.sampo/changesets/emails-tracking.md b/.sampo/changesets/emails-tracking.md index c3f0a6484..e1053e63d 100644 --- a/.sampo/changesets/emails-tracking.md +++ b/.sampo/changesets/emails-tracking.md @@ -2,7 +2,11 @@ pypi/posthog: minor --- -A send with `template_key` now takes `tracking`, which chooses what PostHog tracks for the email. Without it, PostHog counts opens, leaves the links as they are, and captures engagement events. `tracking=True` turns on opens, clicks and engagement events. `tracking=False` turns them all off. A dict such as `{"clicks": True}` or `{"engagement": False}` turns each kind on or off, and a key you leave out keeps its default. The template form doesn't take it. +A send with `template_key` now takes `tracking` and `sensitive`. The template form doesn't take either one. + +`tracking` chooses what PostHog tracks for the email. `tracking=True` turns on opens, clicks and engagement events. `tracking=False` turns them all off. A dict such as `{"clicks": True}` or `{"engagement": False}` turns each kind on or off, and a key you leave out keeps its default. Without it, PostHog counts opens, captures engagement events, and counts clicks only when the email isn't sensitive. + +`sensitive` marks an email that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. A send that sets neither option works exactly as before. ```python posthog.emails.send( @@ -10,12 +14,10 @@ posthog.emails.send( template_key="newsletter", subject="What's new at Acme", html=rendered_html, - tracking={"clicks": True}, + sensitive=False, ) ``` -Clicks are off by default because PostHog can't tell whether a link carries a login or password reset token. Turn them on only when the email's links are safe to send through PostHog's click tracking. - `capture_engagement` is deprecated in favor of `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both. -`tracking` needs PostHog's API support, which is rolling out. Until it reaches your PostHog instance, PostHog refuses a send that sets it. A send without it works as before. +`tracking` and `sensitive` need PostHog's API support, which is rolling out. Until it reaches your PostHog instance, PostHog refuses a send that sets either one. diff --git a/posthog/emails.py b/posthog/emails.py index 90ef639f8..2839a2dd6 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -250,8 +250,9 @@ class EmailTracking(TypedDict, total=False): Args: opens: Counts opens with PostHog's open pixel. Defaults to ``True``. clicks: Counts clicks by sending the email's links through PostHog's - click tracking. Defaults to ``False``. Needs ``opens``: PostHog - refuses a send with ``opens=False`` and ``clicks=True``. + click tracking. Defaults to ``False`` for a sensitive email and + ``True`` for any other. Needs ``opens``: PostHog refuses a send + with ``opens=False`` and ``clicks=True``. engagement: Captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to ``True``. A project whose admin turned engagement @@ -290,18 +291,23 @@ class CodeEmailArgs(_RecipientArgs): captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. + sensitive: Marks the email as sensitive, such as one that carries + login links, reset tokens or codes. A sensitive email keeps its + links as they are unless ``tracking`` turns clicks on, leaves its + subject off engagement events, and keeps its content out of + PostHog's logs. Without it, a send whose ``template_key`` matches + a template saved in PostHog follows that template's setting, and + any other send is sensitive. The template form doesn't take it. tracking: What PostHog tracks for this email. Without it, PostHog - counts opens with its open pixel, leaves the links as they are, - and captures engagement events. ``True`` turns on opens, clicks - and engagement events. ``False`` turns off all tracking, - including kinds PostHog adds later: PostHog can't count the - email's opens or clicks, and captures no engagement events. An - :class:`EmailTracking` dict turns each kind on or off, and a key - you leave out keeps its default. Clicks are off by default - because PostHog can't tell whether a link carries a login or - password reset token. Turn them on only when the email's links - are safe to send through PostHog's click tracking. The template - form doesn't take it. + counts opens with its open pixel, captures engagement events, and + counts clicks only when the email isn't sensitive. ``True`` turns + on opens, clicks and engagement events. ``False`` turns off all + tracking, including kinds PostHog adds later: PostHog can't count + the email's opens or clicks, and captures no engagement events. + An :class:`EmailTracking` dict turns each kind on or off, and a + key you leave out keeps its default. Turn clicks on for a + sensitive email only when its links are safe to send through + PostHog's click tracking. The template form doesn't take it. distinct_id: The recipient's distinct ID in your product. idempotency_key: 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for @@ -319,6 +325,7 @@ class CodeEmailArgs(_RecipientArgs): from_: NotRequired[Optional[str]] reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] capture_engagement: NotRequired[Optional[bool]] + sensitive: NotRequired[Optional[bool]] tracking: NotRequired[Optional[Union[bool, EmailTracking]]] @@ -329,6 +336,7 @@ class CodeEmailArgs(_RecipientArgs): "from_", "reply_to", "capture_engagement", + "sensitive", "tracking", } ) @@ -445,11 +453,11 @@ def _sender(args: Mapping[str, Any]) -> dict[str, Any]: reply_to = _addresses("reply_to", args["reply_to"]) if "reply_to" in args else [] if reply_to: sender["reply_to"] = reply_to - if "capture_engagement" in args: - capture_engagement = args["capture_engagement"] - if not isinstance(capture_engagement, bool): - raise TypeError("capture_engagement must be True or False.") - sender["capture_engagement"] = capture_engagement + for flag in ("capture_engagement", "sensitive"): + if flag in args: + if not isinstance(args[flag], bool): + raise TypeError(f"{flag} must be True or False.") + sender[flag] = args[flag] if "tracking" in args: sender["tracking"] = _tracking(args["tracking"]) return sender diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index 81a78ee79..b13b8a0c6 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -734,9 +734,15 @@ def capture_server() -> Iterator[_CaptureServer]: @pytest.mark.parametrize( "overrides, extra_body", [ - pytest.param({}, {}, id="no_tracking_choice"), + pytest.param({}, {}, id="no_tracking_or_sensitive_choice"), pytest.param( - {"tracking": None, "capture_engagement": None}, {}, id="none_as_left_out" + {"tracking": None, "capture_engagement": None, "sensitive": None}, + {}, + id="none_as_left_out", + ), + pytest.param({"sensitive": True}, {"sensitive": True}, id="marked_sensitive"), + pytest.param( + {"sensitive": False}, {"sensitive": False}, id="marked_not_sensitive" ), pytest.param({"tracking": False}, {"tracking": False}, id="all_tracking_off"), pytest.param({"tracking": True}, {"tracking": True}, id="all_tracking_on"), @@ -752,7 +758,7 @@ def capture_server() -> Iterator[_CaptureServer]: ), ], ) -def test_a_code_send_delivers_its_tracking_choice( +def test_a_code_send_delivers_its_tracking_and_sensitive_choice( capture_server, overrides, extra_body ): host = f"http://127.0.0.1:{capture_server.server_port}" @@ -865,7 +871,18 @@ def handler(request: httpx.Request) -> httpx.Response: }, TypeError, ), + ( + "sensitive_on_template_form", + { + "template_id": TEMPLATE_ID, + "template_key": None, + "subject": None, + "sensitive": False, + }, + TypeError, + ), ("tracking_not_bool_or_dict", {"html": HTML, "tracking": "off"}, TypeError), + ("sensitive_not_bool", {"html": HTML, "sensitive": "yes"}, TypeError), ] ) def test_rejects_a_code_send_that_mixes_or_misses_fields(_name, overrides, error): diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index c9db76c04..064d08788 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -892,6 +892,7 @@ attribute posthog.emails.CodeEmailArgs.capture_engagement: NotRequired[Optional[ attribute posthog.emails.CodeEmailArgs.from_: NotRequired[Optional[str]] attribute posthog.emails.CodeEmailArgs.html: NotRequired[Optional[str]] attribute posthog.emails.CodeEmailArgs.reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] +attribute posthog.emails.CodeEmailArgs.sensitive: NotRequired[Optional[bool]] attribute posthog.emails.CodeEmailArgs.subject: str attribute posthog.emails.CodeEmailArgs.template_key: str attribute posthog.emails.CodeEmailArgs.text: NotRequired[Optional[str]]