Skip to content

: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.

feat(messaging): take template_id and distinct_id at the top of the send body (#126287)

Harley Alexanderc88e365299f8
diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.py
index 948efaa172c7..a3aa34b0cef0 100644
--- a/products/messaging/backend/presentation/views/message_templates.py
+++ b/products/messaging/backend/presentation/views/message_templates.py
@@ -1,5 +1,5 @@
import time
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
from contextlib import AbstractContextManager, nullcontext
from dataclasses import fields as dataclass_fields
from types import SimpleNamespace
@@ -398,23 +398,21 @@ IDEMPOTENCY_KEY_PARAMETER = OpenApiParameter(
TRANSACTIONAL_EMAIL_API_FLAG = "workflows-transactional-email-api"
+DISTINCT_ID_HELP_TEXT = (
+ "Distinct ID of the recipient's person. The email's engagement events (sent, delivered, opened, clicked, "
+ "bounced) and the send itself are recorded against that person. Defaults to the recipient's email address. "
+ "The template can't read the person's properties, so pass everything it needs in `message_data`."
+)
+
+
class TransactionalEmailIdentifiersSerializer(serializers.Serializer):
distinct_id = serializers.CharField(
- required=False,
- allow_null=True,
- allow_blank=True,
- max_length=400,
- help_text="Distinct ID of the recipient's person. The email's engagement events (sent, delivered, opened, "
- "clicked, bounced) and the send itself are recorded against that person. Defaults to the recipient's email "
- "address. The template can't read the person's properties, so pass everything it needs in `message_data`.",
+ required=False, allow_null=True, allow_blank=True, max_length=400, help_text=DISTINCT_ID_HELP_TEXT
)
-class SendTransactionalEmailSerializer(serializers.Serializer):
+class TransactionalEmailMessageSerializer(serializers.Serializer):
to = serializers.EmailField(help_text="Email address of the recipient.")
- identifiers = TransactionalEmailIdentifiersSerializer(
- required=False, help_text="Who the email is for, used to attribute engagement events."
- )
message_data = serializers.DictField(
child=serializers.JSONField(allow_null=True),
required=False,
@@ -424,14 +422,30 @@ class SendTransactionalEmailSerializer(serializers.Serializer):
)
-class SendEmailTemplateSerializer(serializers.Serializer):
- id = serializers.UUIDField(
- help_text="ID of the email template to send. The template must be made transactional first."
+class SendTransactionalEmailSerializer(TransactionalEmailMessageSerializer):
+ identifiers = TransactionalEmailIdentifiersSerializer(
+ required=False, help_text="Who the email is for, used to attribute engagement events."
)
-class SendEmailSerializer(SendTransactionalEmailSerializer):
- template = SendEmailTemplateSerializer(help_text="The transactional email template to send.")
+class SendEmailSerializer(TransactionalEmailMessageSerializer):
+ template_id = serializers.UUIDField(
+ help_text="ID of the email template to send. The template must be made transactional first."
+ )
+ distinct_id = serializers.CharField(
+ required=False, allow_null=True, allow_blank=True, max_length=400, help_text=DISTINCT_ID_HELP_TEXT
+ )
+
+ def to_internal_value(self, data: Any) -> Any:
+ # posthog-node 5.61.0 and posthog 7.81.0 send `template.id` and `identifiers.distinct_id`, so that shape
+ # stays accepted. It is left out of the schema so that new callers use the flat fields.
+ if isinstance(data, Mapping):
+ template, identifiers = data.get("template"), data.get("identifiers")
+ if "template_id" not in data and isinstance(template, Mapping):
+ data = {**data, "template_id": template.get("id")}
+ if "distinct_id" not in data and isinstance(identifiers, Mapping):
+ data = {**data, "distinct_id": identifiers.get("distinct_id")}
+ return super().to_internal_value(data)
class MakeTransactionalSerializer(serializers.Serializer):
@@ -607,7 +621,7 @@ class TransactionalEmailSendMixin:
self.team,
template.id,
to=data["to"],
- distinct_id=(data.get("identifiers") or {}).get("distinct_id") or None,
+ distinct_id=data.get("distinct_id") or (data.get("identifiers") or {}).get("distinct_id") or None,
message_data=data["message_data"],
idempotency_key=idempotency_key,
)
@@ -977,7 +991,7 @@ class MessagingSendViewSet(TransactionalEmailSendMixin, TeamAndOrgViewSetMixin,
responses=SEND_RESPONSES,
summary="Send a transactional email",
description=(
- "Send one transactional email to one recipient from the template named in `template.id`. The template "
+ "Send one transactional email to one recipient from the template named in `template_id`. The template "
"must be made transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. "
"Transactional emails skip opt-outs and frequency caps. Send an `Idempotency-Key` header to retry "
"safely without sending the email twice."
@@ -991,7 +1005,7 @@ class MessagingSendViewSet(TransactionalEmailSendMixin, TeamAndOrgViewSetMixin,
self._require_transactional_email_flag()
with transactional_email_stage("template_lookup"):
try:
- template = get_template(self.team_id, request.validated_data["template"]["id"])
+ template = get_template(self.team_id, request.validated_data["template_id"])
except MessageTemplateMissing:
raise NotFound()
self.check_object_permissions(request, template)
diff --git a/products/messaging/backend/tests/api/test_transactional_email.py b/products/messaging/backend/tests/api/test_transactional_email.py
index 61a67aff020e..0c1618de3de5 100644
--- a/products/messaging/backend/tests/api/test_transactional_email.py
+++ b/products/messaging/backend/tests/api/test_transactional_email.py
@@ -77,10 +77,18 @@ class TestTransactionalEmail(APIBaseTest):
def _send(self, client: APIClient, route: str, body: dict, **kwargs: Any) -> Any:
if route == "send_email":
+ return client.post(self.send_email_url, self._flat(body), format="json", **kwargs)
+ if route == "send_email_nested":
body = {**body, "template": {"id": str(self.template.id)}}
return client.post(self.send_email_url, body, format="json", **kwargs)
return client.post(self.url, body, format="json", **kwargs)
+ def _flat(self, body: dict) -> dict:
+ flat = {k: v for k, v in body.items() if k != "identifiers"}
+ if "identifiers" in body:
+ flat["distinct_id"] = body["identifiers"]["distinct_id"]
+ return {**flat, "template_id": str(self.template.id)}
+
def _psak_client(self, scopes: list[str]) -> APIClient:
raw_token = generate_random_token_secret()
ProjectSecretAPIKey.objects.create(
@@ -101,6 +109,8 @@ class TestTransactionalEmail(APIBaseTest):
("email_only", "template", None, "[email protected]"),
("with_distinct_id_on_send_email", "send_email", {"distinct_id": "user-1"}, "user-1"),
("email_only_on_send_email", "send_email", None, "[email protected]"),
+ ("with_distinct_id_on_send_email_nested", "send_email_nested", {"distinct_id": "user-1"}, "user-1"),
+ ("email_only_on_send_email_nested", "send_email_nested", None, "[email protected]"),
]
)
def test_runs_the_templates_workflow_for_the_recipient(
@@ -123,7 +133,7 @@ class TestTransactionalEmail(APIBaseTest):
stages_after, 1
)
assert response.json() == {"message_id": "invocation-1", "replayed": False}
- assert capture.call_args.kwargs["properties"]["route"] == route
+ assert capture.call_args.kwargs["properties"]["route"] == route.removesuffix("_nested")
assert mock_post.call_args.args[0].endswith(
f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow_id}/transactional_email"
)
@@ -167,7 +177,7 @@ class TestTransactionalEmail(APIBaseTest):
):
self._cdp_accepts(mock_post)
if suffix == "send_email":
- url, body = self.send_email_url, {**self.body, "template": {"id": str(self.template.id)}}
+ url, body = self.send_email_url, self._flat(self.body)
else:
url, body = f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/{suffix}", self.body
@@ -333,7 +343,7 @@ class TestTransactionalEmail(APIBaseTest):
response = self.client.post(
f"/api/projects/{self.team.id}/{path.format(template_id=self.template.id)}",
- {**self.body, "template": {"id": str(self.template.id)}},
+ self._flat(self.body),
format="json",
)
@@ -342,10 +352,10 @@ class TestTransactionalEmail(APIBaseTest):
@parameterized.expand(
[
- ("unknown_template", lambda test: {"id": str(uuid4())}, status.HTTP_404_NOT_FOUND),
+ ("unknown_template", lambda test: str(uuid4()), status.HTTP_404_NOT_FOUND),
(
"another_projects_template",
- lambda test: {"id": str(test._other_team_template().id)},
+ lambda test: str(test._other_team_template().id),
status.HTTP_404_NOT_FOUND,
),
("no_template", lambda test: None, status.HTTP_400_BAD_REQUEST),
@@ -356,7 +366,7 @@ class TestTransactionalEmail(APIBaseTest):
):
self._cdp_accepts(mock_post)
ref = template(self)
- body = {**self.body, "template": ref} if ref else self.body
+ body = {**self.body, "template_id": ref} if ref else self.body
response = self._psak_client(["hog_flow:write"]).post(self.send_email_url, body, format="json")
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index a22ffbc2a0fd..398ca8486eed 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -54,7 +54,13 @@ export interface EmailStatusApi {
*/
export type SendEmailApiMessageData = { [key: string]: unknown }
-export interface TransactionalEmailIdentifiersApi {
+export interface SendEmailApi {
+ /** Email address of the recipient. */
+ to: string
+ /** Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`. */
+ message_data?: SendEmailApiMessageData
+ /** ID of the email template to send. The template must be made transactional first. */
+ template_id: string
/**
* Distinct ID of the recipient's person. The email's engagement events (sent, delivered, opened, clicked, bounced) and the send itself are recorded against that person. Defaults to the recipient's email address. The template can't read the person's properties, so pass everything it needs in `message_data`.
* @maxLength 400
@@ -63,22 +69,6 @@ export interface TransactionalEmailIdentifiersApi {
distinct_id?: string | null
}
-export interface SendEmailTemplateApi {
- /** ID of the email template to send. The template must be made transactional first. */
- id: string
-}
-
-export interface SendEmailApi {
- /** Email address of the recipient. */
- to: string
- /** Who the email is for, used to attribute engagement events. */
- identifiers?: TransactionalEmailIdentifiersApi
- /** Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`. */
- message_data?: SendEmailApiMessageData
- /** The transactional email template to send. */
- template: SendEmailTemplateApi
-}
-
export interface SendTransactionalEmailResponseApi {
/** ID of the queued send. Delivery and engagement are reported against the template asynchronously. */
message_id: string
@@ -897,13 +887,22 @@ export interface MakeTransactionalApi {
*/
export type SendTransactionalEmailApiMessageData = { [key: string]: unknown }
+export interface TransactionalEmailIdentifiersApi {
+ /**
+ * Distinct ID of the recipient's person. The email's engagement events (sent, delivered, opened, clicked, bounced) and the send itself are recorded against that person. Defaults to the recipient's email address. The template can't read the person's properties, so pass everything it needs in `message_data`.
+ * @maxLength 400
+ * @nullable
+ */
+ distinct_id?: string | null
+}
+
export interface SendTransactionalEmailApi {
/** Email address of the recipient. */
to: string
- /** Who the email is for, used to attribute engagement events. */
- identifiers?: TransactionalEmailIdentifiersApi
/** Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`. */
message_data?: SendTransactionalEmailApiMessageData
+ /** Who the email is for, used to attribute engagement events. */
+ identifiers?: TransactionalEmailIdentifiersApi
}
export type MessagingCategoriesListParams = {
diff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.ts
index 86ab98c2f59b..6ba5296b4898 100644
--- a/products/messaging/frontend/generated/api.ts
+++ b/products/messaging/frontend/generated/api.ts
@@ -86,7 +86,7 @@ export const getMessagingSendEmailCreateUrl = (projectId: string) => {
}
/**
- * Send one transactional email to one recipient from the template named in `template.id`. The template must be made transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. Transactional emails skip opt-outs and frequency caps. Send an `Idempotency-Key` header to retry safely without sending the email twice.
+ * Send one transactional email to one recipient from the template named in `template_id`. The template must be made transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. Transactional emails skip opt-outs and frequency caps. Send an `Idempotency-Key` header to retry safely without sending the email twice.
* @summary Send a transactional email
*/
export const messagingSendEmailCreate = async (
diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.ts
index c877138543ae..96e55b0e08de 100644
--- a/products/messaging/frontend/generated/api.zod.ts
+++ b/products/messaging/frontend/generated/api.zod.ts
@@ -10,36 +10,29 @@
import * as zod from 'zod'
/**
- * Send one transactional email to one recipient from the template named in `template.id`. The template must be made transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. Transactional emails skip opt-outs and frequency caps. Send an `Idempotency-Key` header to retry safely without sending the email twice.
+ * Send one transactional email to one recipient from the template named in `template_id`. The template must be made transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. Transactional emails skip opt-outs and frequency caps. Send an `Idempotency-Key` header to retry safely without sending the email twice.
* @summary Send a transactional email
*/
-export const messagingSendEmailCreateBodyIdentifiersOneDistinctIdMax = 400
+export const messagingSendEmailCreateBodyDistinctIdMax = 400
export const MessagingSendEmailCreateBody = /* @__PURE__ */ zod.object({
to: zod.email().describe('Email address of the recipient.'),
- identifiers: zod
- .object({
- distinct_id: zod
- .string()
- .max(messagingSendEmailCreateBodyIdentifiersOneDistinctIdMax)
- .nullish()
- .describe(
- "Distinct ID of the recipient's person. The email's engagement events (sent, delivered, opened, clicked, bounced) and the send itself are recorded against that person. Defaults to the recipient's email address. The template can't read the person's properties, so pass everything it needs in `message_data`."
- ),
- })
- .optional()
- .describe('Who the email is for, used to attribute engagement events.'),
message_data: zod
.record(zod.string(), zod.unknown())
.optional()
.describe(
'Data for the template\'s Liquid placeholders, available as `variables`. For example `{\"reset_link\": \"https:\/\/...\"}` fills `{{ variables.reset_link }}`.'
),
- template: zod
- .object({
- id: zod.uuid().describe('ID of the email template to send. The template must be made transactional first.'),
- })
- .describe('The transactional email template to send.'),
+ template_id: zod
+ .uuid()
+ .describe('ID of the email template to send. The template must be made transactional first.'),
+ distinct_id: zod
+ .string()
+ .max(messagingSendEmailCreateBodyDistinctIdMax)
+ .nullish()
+ .describe(
+ "Distinct ID of the recipient's person. The email's engagement events (sent, delivered, opened, clicked, bounced) and the send itself are recorded against that person. Defaults to the recipient's email address. The template can't read the person's properties, so pass everything it needs in `message_data`."
+ ),
})
export const messagingCategoriesCreateBodyKeyMax = 64
@@ -1334,6 +1327,12 @@ export const messagingTemplatesSendCreateBodyIdentifiersOneDistinctIdMax = 400
export const MessagingTemplatesSendCreateBody = /* @__PURE__ */ zod.object({
to: zod.email().describe('Email address of the recipient.'),
+ message_data: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ 'Data for the template\'s Liquid placeholders, available as `variables`. For example `{\"reset_link\": \"https:\/\/...\"}` fills `{{ variables.reset_link }}`.'
+ ),
identifiers: zod
.object({
distinct_id: zod
@@ -1346,10 +1345,4 @@ export const MessagingTemplatesSendCreateBody = /* @__PURE__ */ zod.object({
})
.optional()
.describe('Who the email is for, used to attribute engagement events.'),
- message_data: zod
- .record(zod.string(), zod.unknown())
- .optional()
- .describe(
- 'Data for the template\'s Liquid placeholders, available as `variables`. For example `{\"reset_link\": \"https:\/\/...\"}` fills `{{ variables.reset_link }}`.'
- ),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ae722e811ada..f87693b32d1c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -111061,7 +111061,13 @@ export namespace Schemas {
*/
export type SendEmailMessageData = {[key: string]: unknown};
- export interface TransactionalEmailIdentifiers {
+ export interface SendEmail {
+ /** Email address of the recipient. */
+ to: string;
+ /** Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`. */
+ message_data?: SendEmailMessageData;
+ /** ID of the email template to send. The template must be made transactional first. */
+ template_id: string;
/**
* Distinct ID of the recipient's person. The email's engagement events (sent, delivered, opened, clicked, bounced) and the send itself are recorded against that person. Defaults to the recipient's email address. The template can't read the person's properties, so pass everything it needs in `message_data`.
* @maxLength 400
@@ -111070,34 +111076,27 @@ export namespace Schemas {
distinct_id?: string | null;
}
- export interface SendEmailTemplate {
- /** ID of the email template to send. The template must be made transactional first. */
- id: string;
- }
-
- export interface SendEmail {
- /** Email address of the recipient. */
- to: string;
- /** Who the email is for, used to attribute engagement events. */
- identifiers?: TransactionalEmailIdentifiers;
- /** Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`. */
- message_data?: SendEmailMessageData;
- /** The transactional email template to send. */
- template: SendEmailTemplate;
- }
-
/**
* Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`.
*/
export type SendTransactionalEmailMessageData = {[key: string]: unknown};
+ export interface TransactionalEmailIdentifiers {
+ /**
+ * Distinct ID of the recipient's person. The email's engagement events (sent, delivered, opened, clicked, bounced) and the send itself are recorded against that person. Defaults to the recipient's email address. The template can't read the person's properties, so pass everything it needs in `message_data`.
+ * @maxLength 400
+ * @nullable
+ */
+ distinct_id?: string | null;
+ }
+
export interface SendTransactionalEmail {
/** Email address of the recipient. */
to: string;
- /** Who the email is for, used to attribute engagement events. */
- identifiers?: TransactionalEmailIdentifiers;
/** Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`. */
message_data?: SendTransactionalEmailMessageData;
+ /** Who the email is for, used to attribute engagement events. */
+ identifiers?: TransactionalEmailIdentifiers;
}
export interface SendTransactionalEmailResponse {