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): send a transactional email over the api (#117786)

Harley Alexandere27da6cac36d
diff --git a/products/messaging/backend/facade/contracts.py b/products/messaging/backend/facade/contracts.py
index 59133d5b431c..f71a960b4d41 100644
--- a/products/messaging/backend/facade/contracts.py
+++ b/products/messaging/backend/facade/contracts.py
@@ -2,6 +2,8 @@ from dataclasses import dataclass
from typing import Any
from uuid import UUID
+from posthog.dataclasses import frozen
+
class UnlayerError(Exception):
pass
@@ -46,3 +48,28 @@ class MarketingTemplate(TransactionalEmailError):
class SenderUnavailable(TransactionalEmailError):
code = "sender_unavailable"
+
+
+class TemplateNotTransactional(TransactionalEmailError):
+ code = "template_not_transactional"
+
+
+class TransactionalEmailPaused(TransactionalEmailError):
+ code = "transactional_email_paused"
+
+
+class InvalidRecipient(TransactionalEmailError):
+ code = "invalid_recipient"
+
+
+class QuotaLimited(TransactionalEmailError):
+ code = "quota_limited"
+
+
+class DeliveryUnavailable(Exception):
+ """The email pipeline did not accept the send. Safe to retry."""
+
+
+@frozen
+class QueuedEmail:
+ message_id: str
diff --git a/products/messaging/backend/facade/transactional_email.py b/products/messaging/backend/facade/transactional_email.py
index d25a22f78160..c8ee6c56d0ce 100644
--- a/products/messaging/backend/facade/transactional_email.py
+++ b/products/messaging/backend/facade/transactional_email.py
@@ -1,17 +1,21 @@
"""Transactional email: a template made sendable over the API, backed by a workflow that runs once per send."""
-from products.messaging.backend.facade.contracts import TransactionalEmailError
+from products.messaging.backend.facade.contracts import DeliveryUnavailable, QueuedEmail, TransactionalEmailError
from products.messaging.backend.services.transactional_email import (
check_transactional_update,
lock_transactional_workflow_id,
make_transactional,
+ send_transactional_email,
sync_transactional_workflow,
)
__all__ = [
+ "DeliveryUnavailable",
+ "QueuedEmail",
"TransactionalEmailError",
"check_transactional_update",
"lock_transactional_workflow_id",
"make_transactional",
+ "send_transactional_email",
"sync_transactional_workflow",
]
diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.py
index 1cd4998111a5..29fb1eb59459 100644
--- a/products/messaging/backend/presentation/views/message_templates.py
+++ b/products/messaging/backend/presentation/views/message_templates.py
@@ -26,8 +26,11 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
-from posthog.event_usage import report_user_action
+from posthog.auth import ProjectSecretAPIKeyAuthentication
+from posthog.event_usage import groups, report_user_action
from posthog.models import User
+from posthog.permissions import is_authenticated_via_project_secret_api_key
+from posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle
from products.cdp.backend.presentation.hog_functions import build_html_wrap_design
from products.messaging.backend.facade.api import (
@@ -49,10 +52,12 @@ from products.messaging.backend.facade.templates import (
update_template,
)
from products.messaging.backend.facade.transactional_email import (
+ DeliveryUnavailable,
TransactionalEmailError,
check_transactional_update,
lock_transactional_workflow_id,
make_transactional,
+ send_transactional_email,
sync_transactional_workflow,
)
from products.messaging.backend.presentation.views.serializers import DesignOperationSerializer
@@ -259,6 +264,32 @@ TEMPLATE_ID_PARAMETER = OpenApiParameter(
TRANSACTIONAL_EMAIL_API_FLAG = "workflows-transactional-email-api"
+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`.",
+ )
+
+
+class SendTransactionalEmailSerializer(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,
+ default=dict,
+ help_text="Data for the template's Liquid placeholders, available as `variables`. "
+ 'For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`.',
+ )
+
+
class MakeTransactionalSerializer(serializers.Serializer):
from_integration_id = serializers.IntegerField(
required=False,
@@ -268,8 +299,14 @@ class MakeTransactionalSerializer(serializers.Serializer):
)
+class SendTransactionalEmailResponseSerializer(serializers.Serializer):
+ message_id = serializers.CharField(
+ help_text="ID of the queued send. Delivery and engagement are reported against the template asynchronously."
+ )
+
+
class TransactionalEmailRejected(exceptions.APIException):
- STATUS_BY_CODE: dict[str, int] = {}
+ STATUS_BY_CODE = {"quota_limited": 429}
# The caller has to change the request. Without this the error handler reports a server error.
default_type = "invalid_request"
@@ -278,6 +315,34 @@ class TransactionalEmailRejected(exceptions.APIException):
super().__init__(detail=str(error), code=error.code)
+class TransactionalEmailUnavailable(exceptions.APIException):
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ default_detail = "The email pipeline is unavailable. Try again shortly."
+ default_code = "delivery_unavailable"
+
+
+class TransactionalEmailBurstThrottle(PersonalOrProjectSecretApiKeyRateThrottle):
+ scope = "transactional_email_burst"
+ rate = "600/minute"
+
+
+class TransactionalEmailSustainedThrottle(PersonalOrProjectSecretApiKeyRateThrottle):
+ scope = "transactional_email_sustained"
+ rate = "20000/hour"
+
+
+class TransactionalEmailTeamBurstThrottle(ProjectSecretApiKeyTeamRateThrottle):
+ """Per-team aggregate across all of a project's secret API keys."""
+
+ scope = "transactional_email_psak_team_burst"
+ rate = "600/minute"
+
+
+class TransactionalEmailTeamSustainedThrottle(ProjectSecretApiKeyTeamRateThrottle):
+ scope = "transactional_email_psak_team_sustained"
+ rate = "20000/hour"
+
+
@extend_schema_view(
retrieve=extend_schema(parameters=[TEMPLATE_ID_PARAMETER]),
update=extend_schema(parameters=[TEMPLATE_ID_PARAMETER]),
@@ -291,8 +356,8 @@ class MessageTemplatesViewSet(
):
scope_object = "hog_flow"
permission_classes = [IsAuthenticated]
- # `design` and `make_transactional` are custom write actions; list them so programmatic callers (MCP/personal
- # API key) get hog_flow:write checked instead of being rejected as an action with no declared scope.
+ # `design` and `send` are custom write actions; list them so programmatic callers (MCP/personal API key)
+ # get hog_flow:write checked instead of being rejected as an action with no declared scope.
scope_object_write_actions = [
"create",
"update",
@@ -300,11 +365,25 @@ class MessageTemplatesViewSet(
"patch",
"destroy",
"design",
+ "send",
"make_transactional",
]
+ authentication_classes = [ProjectSecretAPIKeyAuthentication]
+ # A project secret API key can only send. Template CRUD stays session/personal API key/OAuth only.
+ psak_allowed_actions = ["send"]
serializer_class = MessageTemplateSerializer
+ def get_throttles(self):
+ if self.action == "send":
+ return [
+ TransactionalEmailBurstThrottle(),
+ TransactionalEmailSustainedThrottle(),
+ TransactionalEmailTeamBurstThrottle(),
+ TransactionalEmailTeamSustainedThrottle(),
+ ]
+ return super().get_throttles()
+
def dangerously_get_object(self) -> MessageTemplateRow:
# Team scoping happens in the facade lookup, because the view has no queryset to filter.
# DRF's detail OPTIONS metadata also calls get_object(), so the lookup must live here.
@@ -398,6 +477,9 @@ class MessageTemplatesViewSet(
def _require_workflow_editor(self, hog_flow_id: Any) -> None:
# The template's own access rules don't cover the workflow it sends through, which can carry its own.
+ # A project secret API key has no user to check, and its scope already limits it to sending.
+ if is_authenticated_via_project_secret_api_key(self.request):
+ return
try:
get_workflow(
team_id=self.team_id,
@@ -488,6 +570,56 @@ class MessageTemplatesViewSet(
self._emit_resource_edited(locked)
return Response(self._serialize(locked))
+ @validated_request(
+ SendTransactionalEmailSerializer,
+ responses={
+ 202: OpenApiResponse(response=SendTransactionalEmailResponseSerializer, description="Email queued"),
+ 400: OpenApiResponse(
+ description="The template isn't transactional or its email is paused, or the recipient can't be used"
+ ),
+ 404: OpenApiResponse(description="Template not found"),
+ 429: OpenApiResponse(description="Rate limited, or the project is over its email quota"),
+ 503: OpenApiResponse(description="The email pipeline did not confirm the send"),
+ },
+ summary="Send a transactional email",
+ description=(
+ "Send one transactional email from this template to one recipient. The template must be made "
+ "transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. "
+ "Transactional emails skip opt-outs and frequency caps."
+ ),
+ parameters=[TEMPLATE_ID_PARAMETER],
+ )
+ @action(detail=True, methods=["POST"], pagination_class=None)
+ def send(self, request: Any, *args: Any, **kwargs: Any) -> Response:
+ self._require_transactional_email_flag()
+
+ template = self.get_object()
+ if template.transactional_hog_flow_id:
+ self._require_workflow_editor(template.transactional_hog_flow_id)
+ data = request.validated_data
+ outcome: dict[str, Any] = {"outcome": "error"}
+ try:
+ queued = send_transactional_email(
+ self.team,
+ template.id,
+ to=data["to"],
+ distinct_id=(data.get("identifiers") or {}).get("distinct_id") or None,
+ message_data=data["message_data"],
+ )
+ outcome = {"outcome": "queued"}
+ except TransactionalEmailError as e:
+ outcome = {"outcome": "rejected", "error_code": e.code}
+ raise TransactionalEmailRejected(e)
+ except DeliveryUnavailable:
+ outcome = {"outcome": "unavailable"}
+ raise TransactionalEmailUnavailable() from None
+ finally:
+ self._report_transactional_email_send(request, template, outcome)
+ return Response(
+ SendTransactionalEmailResponseSerializer(queued).data,
+ status=status.HTTP_202_ACCEPTED,
+ )
+
def _require_transactional_email_flag(self) -> None:
if not posthoganalytics.feature_enabled(
TRANSACTIONAL_EMAIL_API_FLAG,
@@ -546,3 +678,24 @@ class MessageTemplatesViewSet(
except Exception as e:
logger.warning("Failed to capture message template usage event", error=str(e))
return Response(self._serialize(updated))
+
+ def _report_transactional_email_send(
+ self, request: Any, template: MessageTemplateRow, outcome: dict[str, Any]
+ ) -> None:
+ # report_user_action drops the synthetic user behind a project secret API key, so capture directly.
+ try:
+ posthoganalytics.capture(
+ distinct_id=request.user.distinct_id,
+ event="transactional email api send",
+ properties={
+ "template_id": str(template.id),
+ "team_id": self.team_id,
+ "auth_method": "project_secret_api_key"
+ if is_authenticated_via_project_secret_api_key(request)
+ else "user",
+ **outcome,
+ },
+ groups=groups(self.organization, self.team),
+ )
+ except Exception as e:
+ logger.warning("Failed to capture transactional email usage event", error=str(e))
diff --git a/products/messaging/backend/services/transactional_email.py b/products/messaging/backend/services/transactional_email.py
index f8889bccca18..ef62de81b0d6 100644
--- a/products/messaging/backend/services/transactional_email.py
+++ b/products/messaging/backend/services/transactional_email.py
@@ -8,9 +8,23 @@ from django.db import transaction
import structlog
-from posthog.plugins.plugin_server_api import reload_hog_flows_on_workers
+from posthog.models.team import Team
+from posthog.plugins.plugin_server_api import (
+ reload_hog_flows_on_workers,
+ send_transactional_email as run_transactional_workflow,
+)
-from products.messaging.backend.facade.contracts import MarketingTemplate, SenderUnavailable, TemplateNotSendable
+from products.messaging.backend.facade.contracts import (
+ DeliveryUnavailable,
+ InvalidRecipient,
+ MarketingTemplate,
+ QueuedEmail,
+ QuotaLimited,
+ SenderUnavailable,
+ TemplateNotSendable,
+ TemplateNotTransactional,
+ TransactionalEmailPaused,
+)
from products.messaging.backend.models import MessageCategory, MessageTemplate
from products.messaging.backend.models.message_category import MessageCategoryType
from products.workflows.backend.facade.api import WorkflowNotFound, get_workflow_summary
@@ -157,3 +171,57 @@ def sync_transactional_workflow(team_id: int, template_id: UUID, *, user_id: int
raise TemplateNotSendable("The template needs a subject and a body to send.") from e
except TransactionalEmailSenderUnavailable as e:
raise SenderUnavailable("No verified email sender. Verify a sending domain first.") from e
+
+
+def _transactional_workflow_id(team_id: int, template_id: UUID) -> UUID:
+ template = MessageTemplate.objects.get(team_id=team_id, id=template_id, deleted=False)
+ if not template.transactional_hog_flow_id:
+ raise TemplateNotTransactional("The template isn't transactional. Make it transactional to send it.")
+ # A category's type can change after the template was made transactional.
+ check_sendable(
+ team_id,
+ template_type=template.type,
+ content=template.content,
+ message_category_id=template.message_category_id,
+ )
+ try:
+ workflow = get_workflow_summary(team_id=team_id, workflow_id=str(template.transactional_hog_flow_id))
+ except WorkflowNotFound as e:
+ raise TransactionalEmailPaused("The template's transactional email no longer exists.") from e
+ if workflow.status != "active":
+ raise TransactionalEmailPaused("The template's transactional email isn't active.")
+ return template.transactional_hog_flow_id
+
+
+def send_transactional_email(
+ team: Team, template_id: UUID, *, to: str, distinct_id: str | None, message_data: dict[str, Any]
+) -> QueuedEmail:
+ # Defense in depth: the workflow reads the recipient from an event property, which Liquid outputs as typed.
+ if "{" in to or "}" in to:
+ raise InvalidRecipient("The recipient address can't contain { or }.")
+
+ hog_flow_id = _transactional_workflow_id(team.id, template_id)
+ payload = {
+ "to": to,
+ # The recipient is the person the send is tracked against. Without a distinct_id, the address is one.
+ "distinct_id": distinct_id or to,
+ "variables": message_data,
+ }
+ try:
+ response = run_transactional_workflow(team.id, str(hog_flow_id), payload)
+ except Exception as e:
+ logger.exception("transactional_email_queue_failed", team_id=team.id, template_id=str(template_id))
+ raise DeliveryUnavailable() from e
+
+ if response.status_code != 202:
+ if response.status_code == 429:
+ raise QuotaLimited("The project is over its email quota.")
+ logger.error(
+ "transactional_email_queue_rejected",
+ team_id=team.id,
+ template_id=str(template_id),
+ status_code=response.status_code,
+ )
+ raise DeliveryUnavailable()
+
+ return QueuedEmail(message_id=str(response.json()["invocation_id"]))
diff --git a/products/messaging/backend/tests/api/test_transactional_email.py b/products/messaging/backend/tests/api/test_transactional_email.py
index 876a0dbdc125..7f6cf43cf933 100644
--- a/products/messaging/backend/tests/api/test_transactional_email.py
+++ b/products/messaging/backend/tests/api/test_transactional_email.py
@@ -3,14 +3,18 @@ from uuid import uuid4
import pytest
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
+import requests
from parameterized import parameterized
from rest_framework import status
+from rest_framework.test import APIClient
from posthog.constants import AvailableFeature
-from posthog.models import OrganizationMembership, User
+from posthog.models import OrganizationMembership, ProjectSecretAPIKey, User
from posthog.models.integration import Integration
+from posthog.models.personal_api_key import hash_key_value
+from posthog.models.utils import generate_random_token_secret
from products.access_control.backend.facade.testing import create_access_control
from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryType
@@ -36,6 +40,12 @@ class TestTransactionalEmail(APIBaseTest):
self.hog_flow_id = make_transactional(
self.team.id, self.template.id, user_id=self.user.id, from_integration_id=None
)
+ self.url = f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/send/"
+ self.body = {
+ "identifiers": {"distinct_id": "user-1"},
+ "message_data": {"link": "https://example.com/reset", "nickname": None},
+ }
def _template(self, content: dict | None = None) -> MessageTemplate:
return MessageTemplate.objects.create(
@@ -51,6 +61,128 @@ class TestTransactionalEmail(APIBaseTest):
assert response.status_code == status.HTTP_200_OK, response.json()
return response.json()
+ def _cdp_accepts(self, mock_post: MagicMock, invocation_id: str = "invocation-1") -> None:
+ mock_post.return_value = MagicMock(status_code=202, json=lambda: {"invocation_id": invocation_id})
+
+ def _psak_client(self, scopes: list[str]) -> APIClient:
+ raw_token = generate_random_token_secret()
+ ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="transactional email",
+ secure_value=hash_key_value(raw_token),
+ scopes=scopes,
+ mask_value=f"{raw_token[:4]}...{raw_token[-4:]}",
+ )
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw_token}")
+ return client
+
+ @parameterized.expand(
+ [
+ ("with_distinct_id", {"distinct_id": "user-1"}, "user-1"),
+ # Without a distinct_id the recipient's address is the person the send is tracked against.
+ ("email_only", None, "[email protected]"),
+ ]
+ )
+ def test_runs_the_templates_workflow_for_the_recipient(
+ self, mock_post, _flag, _capture, _name, identifiers, expected_distinct_id
+ ):
+ self._cdp_accepts(mock_post)
+ body = (
+ {**self.body, "identifiers": identifiers}
+ if identifiers
+ else {k: v for k, v in self.body.items() if k != "identifiers"}
+ )
+
+ response = self._psak_client(["hog_flow:write"]).post(self.url, body, format="json")
+
+ assert response.status_code == status.HTTP_202_ACCEPTED, response.json()
+ assert response.json() == {"message_id": "invocation-1"}
+ assert mock_post.call_args.args[0].endswith(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow_id}/transactional_email"
+ )
+ assert mock_post.call_args.kwargs["json"] == {
+ "distinct_id": expected_distinct_id,
+ "variables": {"link": "https://example.com/reset", "nickname": None},
+ }
+
+ @parameterized.expand(
+ [
+ ("send_with_write_scope", "post", "send/", ["hog_flow:write"], status.HTTP_202_ACCEPTED),
+ ("send_with_read_scope", "post", "send/", ["hog_flow:read"], status.HTTP_403_FORBIDDEN),
+ ("retrieve_is_not_a_psak_action", "get", "", ["hog_flow:write"], status.HTTP_403_FORBIDDEN),
+ (
+ "make_transactional_is_not_a_psak_action",
+ "post",
+ "make_transactional/",
+ ["hog_flow:write"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ ]
+ )
+ def test_project_secret_api_key_can_only_send(
+ self, mock_post, _flag, _capture, _name, method, suffix, scopes, expected_status
+ ):
+ self._cdp_accepts(mock_post)
+ url = f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/{suffix}"
+
+ response = getattr(self._psak_client(scopes), method)(
+ url, self.body if method == "post" else None, format="json"
+ )
+
+ assert response.status_code == expected_status, response.json()
+
+ @parameterized.expand(
+ [
+ ("not_transactional", "template_not_transactional"),
+ ("workflow_archived", "transactional_email_paused"),
+ ("category_turned_marketing", "marketing_template"),
+ ("liquid_in_recipient", "invalid_recipient"),
+ ]
+ )
+ def test_rejects_a_send_it_cannot_make(self, mock_post, _flag, _capture, case, expected_code):
+ url, body = self.url, dict(self.body)
+ if case == "not_transactional":
+ url = f"/api/projects/{self.team.id}/messaging_templates/{self._template().id}/send/"
+ elif case == "workflow_archived":
+ archived = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow_id}", {"status": "archived"}
+ )
+ assert archived.status_code == status.HTTP_200_OK, archived.json()
+ elif case == "category_turned_marketing":
+ category = MessageCategory.objects.create(
+ team=self.team, key="account", name="Account", category_type=MessageCategoryType.TRANSACTIONAL
+ )
+ MessageTemplate.objects.filter(id=self.template.id).update(message_category=category)
+ MessageCategory.objects.filter(id=category.id).update(category_type=MessageCategoryType.MARKETING)
+ elif case == "liquid_in_recipient":
+ body["to"] = "{{person.properties.email}}@example.com"
+
+ response = self.client.post(url, body, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["code"] == expected_code
+ assert response.json()["type"] == "invalid_request"
+ mock_post.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("timeout", requests.ReadTimeout()),
+ ("cdp_api_error", MagicMock(status_code=500)),
+ ]
+ )
+ def test_a_send_the_pipeline_does_not_confirm_is_unavailable(self, mock_post, _flag, _capture, _name, outcome):
+ if isinstance(outcome, Exception):
+ mock_post.side_effect = outcome
+ else:
+ mock_post.return_value = outcome
+
+ response = self.client.post(self.url, self.body, format="json")
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert response.json()["code"] == "delivery_unavailable"
+
@parameterized.expand(
[
("update", "", {"name": "Reset"}),
@@ -102,16 +234,24 @@ class TestTransactionalEmail(APIBaseTest):
assert edited.json()["transactional_hog_flow_id"] is None
assert remade.json()["transactional_hog_flow_id"] not in (None, str(self.hog_flow_id))
- def test_is_hidden_while_the_flag_is_off(self, mock_post, flag, _capture):
+ def test_reports_quota_limited_teams(self, mock_post, _flag, _capture):
+ mock_post.return_value = MagicMock(status_code=429, json=lambda: {"error": "quota_limited"})
+
+ response = self.client.post(self.url, self.body, format="json")
+
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ assert response.json()["code"] == "quota_limited"
+
+ @parameterized.expand([("send", "send/"), ("make_transactional", "make_transactional/")])
+ def test_is_hidden_while_the_flag_is_off(self, mock_post, flag, _capture, _name, suffix):
flag.return_value = False
response = self.client.post(
- f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/make_transactional/",
- {},
- format="json",
+ f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/{suffix}", self.body, format="json"
)
assert response.status_code == status.HTTP_404_NOT_FOUND
+ mock_post.assert_not_called()
def test_making_a_template_transactional_creates_its_workflow_once(self, mock_post, _flag, _capture):
template = self._template()
@@ -275,10 +415,11 @@ class TestTransactionalEmailWorkflowAccess(APIBaseTest):
@parameterized.expand(
[
+ ("send", "post", "send/", {"to": "[email protected]"}),
("update", "patch", "", {"content": {"email": {"subject": "New", "html": "<p>New</p>"}}}),
]
)
- def test_a_member_denied_the_workflow_cannot_change_it(self, mock_post, _flag, _name, method, suffix, body):
+ def test_a_member_denied_the_workflow_cannot_send_or_change_it(self, mock_post, _flag, _name, method, suffix, body):
url = f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/{suffix}"
response = getattr(self.client, method)(url, body, format="json")
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index 0576f0265791..79ab7aa3efca 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -510,6 +510,34 @@ export interface MakeTransactionalApi {
from_integration_id?: number | null
}
+/**
+ * Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`.
+ */
+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
+}
+
+export interface SendTransactionalEmailResponseApi {
+ /** ID of the queued send. Delivery and engagement are reported against the template asynchronously. */
+ message_id: string
+}
+
export type MessagingCategoriesListParams = {
/**
* Number of results to return per page.
diff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.ts
index 6fe995268852..6f4a2bd8cc79 100644
--- a/products/messaging/frontend/generated/api.ts
+++ b/products/messaging/frontend/generated/api.ts
@@ -33,6 +33,8 @@ import type {
PatchedMessageTemplateApi,
PreferencesLinkApi,
RemoveOptOutRequestApi,
+ SendTransactionalEmailApi,
+ SendTransactionalEmailResponseApi,
WebhookUrlApi,
} from './api.schemas'
@@ -744,3 +746,25 @@ export const messagingTemplatesMakeTransactionalCreate = async (
body: JSON.stringify(makeTransactionalApi),
})
}
+
+export const getMessagingTemplatesSendCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/messaging_templates/${id}/send/`
+}
+
+/**
+ * Send one transactional email from this template to one recipient. The template must be made transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. Transactional emails skip opt-outs and frequency caps.
+ * @summary Send a transactional email
+ */
+export const messagingTemplatesSendCreate = async (
+ projectId: string,
+ id: string,
+ sendTransactionalEmailApi: SendTransactionalEmailApi,
+ options?: RequestInit
+): Promise<SendTransactionalEmailResponseApi> => {
+ return apiMutator<SendTransactionalEmailResponseApi>(getMessagingTemplatesSendCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(sendTransactionalEmailApi),
+ })
+}
diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.ts
index f9e744c865a8..9957e6349bc4 100644
--- a/products/messaging/frontend/generated/api.zod.ts
+++ b/products/messaging/frontend/generated/api.zod.ts
@@ -593,3 +593,31 @@ export const MessagingTemplatesMakeTransactionalCreateBody = /* @__PURE__ */ zod
"ID of the verified email sender integration the email is sent from. Defaults to the project's default sender."
),
})
+
+/**
+ * Send one transactional email from this template to one recipient. The template must be made transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. Transactional emails skip opt-outs and frequency caps.
+ * @summary Send a transactional email
+ */
+export const messagingTemplatesSendCreateBodyIdentifiersOneDistinctIdMax = 400
+
+export const MessagingTemplatesSendCreateBody = /* @__PURE__ */ zod.object({
+ to: zod.email().describe('Email address of the recipient.'),
+ identifiers: zod
+ .object({
+ distinct_id: zod
+ .string()
+ .max(messagingTemplatesSendCreateBodyIdentifiersOneDistinctIdMax)
+ .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 }}`.'
+ ),
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index cf7330f363fb..a95e7527b41a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -101418,6 +101418,34 @@ export namespace Schemas {
channel_id: string;
}
+ /**
+ * 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;
+ }
+
+ export interface SendTransactionalEmailResponse {
+ /** ID of the queued send. Delivery and engagement are reported against the template asynchronously. */
+ message_id: string;
+ }
+
export interface ServiceAccountAccessUpdate {
/** Gateway server to share or stop sharing. */
gateway_server_id: string;