:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(email): pass team_name and customer_id to transactional email footer (#73130)
Alex Liderae7b588896d9
diff --git a/posthog/email.py b/posthog/email.pyindex 3c203ecbf39b..c8118a93391c 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -7,7 +7,7 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Any, Literal, Optionalif TYPE_CHECKING:- from posthog.models import User+ from posthog.models import Organization, Team, Userfrom django.conf import settingsfrom django.core import exceptions, mail@@ -27,7 +27,7 @@ from prometheus_client import Counterfrom posthog.celery_queues import CeleryQueuefrom posthog.exceptions_capture import capture_exception-from posthog.helpers.email_utils import sanitize_email_string+from posthog.helpers.email_utils import sanitize_display_name, sanitize_email_stringfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.messaging import MessagingRecord@@ -154,6 +154,37 @@ CUSTOMER_IO_TEMPLATE_ID_MAP = {}+def get_email_team_and_org_context(+ team: Optional["Team"] = None,+ organization: Optional["Organization"] = None,+) -> dict[str, str]:+ """+ team_name, organization_name, and customer_id (the billing customer) for a transactional+ email. Spread it into template_context whenever a team or organization is in scope. Absent+ values are omitted so templates render only what's present, and both names are sanitized,+ so one that happens to be a URL degrades to a placeholder instead of rendering as a link.+ """+ if organization is None and team is not None:+ organization = team.organization+ context: dict[str, str] = {}+ if team is not None and team.name:+ context["team_name"] = sanitize_display_name(+ team.name,+ fallback="your project",+ context={"helper": "get_email_team_and_org_context", "field": "team_name"},+ )+ if organization is not None:+ if organization.name:+ context["organization_name"] = sanitize_display_name(+ organization.name,+ fallback="your organization",+ context={"helper": "get_email_team_and_org_context", "field": "organization_name"},+ )+ if organization.customer_id:+ context["customer_id"] = organization.customer_id+ return context++def get_customer_io_template_id(template_name: str) -> str:"""Get Customer.io template ID from template name"""template_id = CUSTOMER_IO_TEMPLATE_ID_MAP.get(template_name)diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 23672c995a70..2bc8b13bcc1f 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -18,7 +18,7 @@ from prometheus_client import Counter, Histogramfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.cloud_utils import is_cloudfrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMES, INVITE_DAYS_VALIDITY-from posthog.email import EMAIL_TASK_KWARGS, EmailMessage, is_email_available+from posthog.email import EMAIL_TASK_KWARGS, EmailMessage, get_email_team_and_org_context, is_email_availablefrom posthog.event_usage import groupsfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.email_utils import sanitize_display_name, sanitize_message_body@@ -298,6 +298,7 @@ def send_invite(invite_id: str) -> None:"invitee_first_name": invitee_first_name,"invite_message": invite_message,"url": f"{settings.SITE_URL}/signup/{invite_id}",+ **get_email_team_and_org_context(organization=invite.organization),},reply_to=invite.created_by.email if invite.created_by and invite.created_by.email else "",)@@ -378,12 +379,6 @@ def send_member_join(invitee_uuid: str, organization_id: str) -> None:fallback="",context={"task": "send_member_join", "field": "invitee_last_name", **log_context},)- organization_name = sanitize_display_name(- organization.name,- fallback="your organization",- context={"task": "send_member_join", "field": "organization_name", **log_context},- )-campaign_key: str = f"member_join_email_org_{organization_id}_user_{invitee_uuid}"message = EmailMessage(use_http=True,@@ -395,7 +390,7 @@ def send_member_join(invitee_uuid: str, organization_id: str) -> None:"organization": organization,"invitee_first_name": invitee_first_name,"invitee_last_name": invitee_last_name,- "organization_name": organization_name,+ **get_email_team_and_org_context(organization=organization),},)for user in members_to_email:@@ -1043,12 +1038,12 @@ def send_wizard_pr_ready_email(run_id: str) -> None:"pr_url": context.pr_url,"repository": context.repository or "","first_name": user.first_name or "",- "organization_name": team.organization.name,"project_name": team.name,"branch_name": context.branch or "","task_id": str(context.task_id),"run_id": str(context.run_id),"site_url": settings.SITE_URL,+ **get_email_team_and_org_context(team=team),}message = EmailMessage(use_http=True,@@ -1820,6 +1815,7 @@ def send_feature_flags_secure_api_key_exposed(team_id: int, mask_value: str, mor"more_info": more_info,"mask_value": mask_value,"url": f"{settings.SITE_URL}/project/{team.pk}/settings/project-feature-flags",+ **get_email_team_and_org_context(team=team),},)for membership in memberships_to_email:@@ -1853,6 +1849,7 @@ def send_project_secret_api_key_exposed("more_info": more_info,"mask_value": old_mask_value,"url": f"{settings.SITE_URL}/project/{team.pk}/settings/environment-secret-api-keys",+ **get_email_team_and_org_context(team=team),},)for membership in memberships_to_email:@@ -1939,12 +1936,12 @@ def send_new_ticket_notification(ticket_id: str, team_id: int, first_message_consubject=f"[Ticket #{ticket.ticket_number}] New support ticket in {team.name}",template_name="new_conversation_ticket",template_context={- "team_name": team.name,"ticket_number": ticket.ticket_number,"customer_name": customer_name,"customer_email": customer_email,"first_message": first_message_content[:500] if first_message_content else "","ticket_url": ticket_url,+ **get_email_team_and_org_context(team=team),},)@@ -1976,8 +1973,8 @@ def send_conversation_restore_email(email: str, team_id: int, restore_url: str)subject=f"Restore your conversations with {team.name}",template_name="conversation_restore",template_context={- "team_name": team.name,"restore_url": restore_url,+ **get_email_team_and_org_context(team=team),},)@@ -2005,6 +2002,7 @@ def send_project_deleted_email(template_name="project_deleted",template_context={"project_name": project_name,+ "team_name": project_name,"site_url": settings.SITE_URL,},)@@ -2345,8 +2343,8 @@ def send_integration_access_request(team_id: int, requesting_user_id: int, kind:"integration_kind": kind,"reason": sanitized_reason,"org_name": org_name,- "team_name": team.name,"connect_url": f"{settings.SITE_URL}/project/{team_id}/integrations/{kind}",+ **get_email_team_and_org_context(team=team),},reply_to=requester.email or "",)@@ -2370,12 +2368,6 @@ def send_posthog_ai_access_request(organization_id: str, requesting_user_id: intfallback="A teammate",context={"task": "send_posthog_ai_access_request", "field": "requester_first_name", **log_context},)- org_name = sanitize_display_name(- organization.name,- fallback="your organization",- context={"task": "send_posthog_ai_access_request", "field": "organization_name", **log_context},- )-# AI consent is an org-level setting reachable from any project; prefer the requester's# current project so the link feels familiar, falling back to any project in the org.current_team = requester.current_team@@ -2411,8 +2403,8 @@ def send_posthog_ai_access_request(organization_id: str, requesting_user_id: inttemplate_context={"requester_name": requester_name,"requester_email": requester.email or "",- "organization_name": org_name,"posthog_ai_url": posthog_ai_url,+ **get_email_team_and_org_context(organization=organization),},reply_to=requester.email or "",)diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex f4f509afdcde..5998cebd0cb8 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -437,6 +437,7 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):"task_id": str(task.id),"run_id": str(run.id),"site_url": settings.SITE_URL,+ "team_name": team.name,"utm_tags": "utm_source=posthog&utm_medium=email&utm_campaign=wizard_pr_ready",}diff --git a/posthog/temporal/proxy_service/common.py b/posthog/temporal/proxy_service/common.pyindex c398418c3d5e..e35a993a25a1 100644--- a/posthog/temporal/proxy_service/common.py+++ b/posthog/temporal/proxy_service/common.py@@ -205,7 +205,7 @@ class SendProxyCreatedEmailInputs:@activity.defndef activity_send_proxy_created_email(inputs: SendProxyCreatedEmailInputs):"""Send an email notification when a reverse proxy has been successfully provisioned."""- from posthog.email import EmailMessage, is_email_available+ from posthog.email import EmailMessage, get_email_team_and_org_context, is_email_availabletry:connection.connect()@@ -213,7 +213,9 @@ def activity_send_proxy_created_email(inputs: SendProxyCreatedEmailInputs):if not is_email_available():return- record = ProxyRecord.objects.select_related("created_by").filter(id=inputs.proxy_record_id).first()+ record = (+ ProxyRecord.objects.select_related("created_by", "organization").filter(id=inputs.proxy_record_id).first()+ )if record is None or record.created_by is None or not record.created_by.email:return@@ -226,6 +228,7 @@ def activity_send_proxy_created_email(inputs: SendProxyCreatedEmailInputs):"user_name": user.first_name,"domain": inputs.domain,"settings_url": f"{settings.SITE_URL}/settings/organization-proxy",+ **get_email_team_and_org_context(organization=record.organization),},use_http=True,)diff --git a/posthog/test/test_email.py b/posthog/test/test_email.pyindex 8fc335268caa..d4767c442c4c 100644--- a/posthog/test/test_email.py+++ b/posthog/test/test_email.py@@ -26,6 +26,7 @@ from posthog.email import (_send_email,_send_via_http,_send_via_smtp,+ get_email_team_and_org_context,sanitize_email_properties,)from posthog.models import Organization, Person, Team, User@@ -37,6 +38,47 @@ from posthog.test.persons import ()+class TestEmailTeamAndOrgContext(BaseTest):+ def test_team_derives_org_name_and_customer_id_from_org(self):+ self.organization.customer_id = "cus_123"+ self.organization.save()+ assert get_email_team_and_org_context(team=self.team) == {+ "team_name": self.team.name,+ "organization_name": self.organization.name,+ "customer_id": "cus_123",+ }++ def test_organization_only_yields_org_name_and_customer_id(self):+ self.organization.customer_id = "cus_123"+ self.organization.save()+ assert get_email_team_and_org_context(organization=self.organization) == {+ "organization_name": self.organization.name,+ "customer_id": "cus_123",+ }++ @parameterized.expand(+ [+ ("team_name", "your project"),+ ("organization_name", "your organization"),+ ]+ )+ def test_url_name_falls_back_to_a_placeholder(self, field: str, expected: str):+ self.team.name = "https://acme.example.com"+ self.team.save()+ self.organization.name = "https://acme.example.com"+ self.organization.save()+ assert get_email_team_and_org_context(team=self.team)[field] == expected++ def test_blank_values_are_omitted_so_templates_render_only_whats_present(self):+ self.organization.customer_id = None+ self.organization.save()+ assert get_email_team_and_org_context() == {}+ assert get_email_team_and_org_context(team=self.team) == {+ "team_name": self.team.name,+ "organization_name": self.organization.name,+ }++class TestEmail(BaseTest):def create_person(self, team: Team, base_distinct_id: str = "") -> Person:person = create_test_person(team=team)diff --git a/products/approvals/backend/notifications.py b/products/approvals/backend/notifications.pyindex f4e331e37fee..d6dce82aea5e 100644--- a/products/approvals/backend/notifications.py+++ b/products/approvals/backend/notifications.py@@ -2,7 +2,7 @@ from typing import TYPE_CHECKINGfrom structlog import get_logger-from posthog.email import EmailMessage, is_email_available+from posthog.email import EmailMessage, get_email_team_and_org_context, is_email_availablefrom posthog.models import Userfrom posthog.utils import absolute_uri@@ -124,7 +124,7 @@ def _send_approval_email(template_context = {"change_request_url": change_request_url,- "team_name": change_request.team.name,+ **get_email_team_and_org_context(team=change_request.team),}if extra_context:template_context.update(extra_context)diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.pyindex efeef5570ef6..f7f313c2afa0 100644--- a/products/legal_documents/backend/logic/__init__.py+++ b/products/legal_documents/backend/logic/__init__.py@@ -16,7 +16,7 @@ import structlogimport posthoganalyticsfrom posthog.cloud_utils import get_cached_instance_license-from posthog.email import EmailMessage, is_email_available+from posthog.email import EmailMessage, get_email_team_and_org_context, is_email_availablefrom posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.organization import Organization, OrganizationMembership@@ -247,8 +247,8 @@ def _send_baa_signed_ai_disabled_email(organization: Organization, document: Legtemplate_name=BAA_SIGNED_AI_DISABLED_TEMPLATE,subject=f"AI features have been disabled for {organization.name}",template_context={- "organization_name": organization.name,"ai_settings_url": f"{settings.SITE_URL}/settings/organization-details#organization-ai-consent",+ **get_email_team_and_org_context(organization=organization),},use_http=True,)diff --git a/products/tasks/backend/loop_notifications.py b/products/tasks/backend/loop_notifications.pyindex dbacbbadcd72..6a11b1cc0adb 100644--- a/products/tasks/backend/loop_notifications.py+++ b/products/tasks/backend/loop_notifications.py@@ -19,7 +19,7 @@ from django.db import transactionimport structlogfrom slack_sdk.errors import SlackApiError-from posthog.email import EmailMessage, is_email_available+from posthog.email import EmailMessage, get_email_team_and_org_context, is_email_availablefrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.redis import get_clientfrom posthog.tasks.push_notifications import send_user_push@@ -161,6 +161,7 @@ def _send_email("event_body": body,"run_url": str(payload.get("url") or ""),"report": str(payload.get("report") or ""),+ **get_email_team_and_org_context(team=loop.team),}message = EmailMessage(campaign_key=campaign_key,