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(workflows): show api, node and python tabs in the transactional email snippet (#126226)

Harley Alexander1d8b4250b8a4
diff --git a/products/workflows/frontend/TemplateLibrary/TransactionalEmailApiExample.tsx b/products/workflows/frontend/TemplateLibrary/TransactionalEmailApiExample.tsx
index 8f35f9e076fd..6c1bd060c354 100644
--- a/products/workflows/frontend/TemplateLibrary/TransactionalEmailApiExample.tsx
+++ b/products/workflows/frontend/TemplateLibrary/TransactionalEmailApiExample.tsx
@@ -1,11 +1,27 @@
import { useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useState } from 'react'
-import { Link } from '@posthog/lemon-ui'
+import { LemonSegmentedButton, Link } from '@posthog/lemon-ui'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { apiHostOrigin } from 'lib/utils/apiHost'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+type SnippetLanguage = 'api' | 'node' | 'python'
+
+const LANGUAGE_OPTIONS: { value: SnippetLanguage; label: string; 'data-attr': string }[] = [
+ { value: 'api', label: 'API', 'data-attr': 'transactional-email-api-example-api' },
+ { value: 'node', label: 'Node.js', 'data-attr': 'transactional-email-api-example-node' },
+ { value: 'python', label: 'Python', 'data-attr': 'transactional-email-api-example-python' },
+]
+
+const INSTALL_COMMANDS: Partial<Record<SnippetLanguage, string>> = {
+ node: 'npm install posthog-node@^5.61.2',
+ python: 'pip install "posthog>=7.81.2"',
+}
+
export function TransactionalEmailApiExample({
templateId,
variables,
@@ -14,20 +30,83 @@ export function TransactionalEmailApiExample({
/** The email's `{{ variables.* }}` names. The snippet shows a sample when the email uses none. */
variables?: string[]
}): JSX.Element {
- const { currentTeamIdStrict } = useValues(teamLogic)
- const messageData = variables?.length
- ? `{ ${variables.map((name) => `"${name}": "..."`).join(', ')} }`
- : '{ "first_name": "Jane", "reset_link": "https://example.com/reset" }'
- const snippet = `curl -X POST ${window.location.origin}/api/projects/${currentTeamIdStrict}/messaging/send/email/ \\
+ const { currentTeam, currentTeamIdStrict } = useValues(teamLogic)
+ const [language, setLanguage] = useState<SnippetLanguage>('api')
+
+ const projectToken = currentTeam?.api_token ?? '<ph_project_api_key>'
+ const host = apiHostOrigin()
+ // The SDKs find the app host themselves only on PostHog Cloud, where the ingestion host differs from the app's.
+ const appHost = host === window.location.origin ? host : null
+ const data: [string, string][] = variables?.length
+ ? variables.map((name) => [name, '...'])
+ : [
+ ['first_name', 'Jane'],
+ ['reset_link', 'https://example.com/reset'],
+ ]
+ const dataEntries = (separator: string): string =>
+ data.map(([name, value]) => `"${name}"${separator}"${value}"`).join(', ')
+
+ const snippets: Record<SnippetLanguage, { language: Language; code: string }> = {
+ node: {
+ language: Language.JavaScript,
+ code: `import { PostHog } from 'posthog-node'
+
+const posthog = new PostHog('${projectToken}', {
+ host: '${host}',${appHost ? `\n appHost: '${appHost}',` : ''}
+ secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY,
+ // This client only sends email, so it doesn't poll flag definitions with the secret key
+ enableLocalEvaluation: false,
+})
+
+const { data, error } = await posthog.emails.send({
+ templateId: '${templateId}',
+ templateData: { ${dataEntries(': ')} },
+ distinctId: 'jane-distinct-id',
+ idempotencyKey: 'password-reset-123',
+})
+if (error) {
+ throw error
+}
+console.log(data.id)`,
+ },
+ python: {
+ language: Language.Python,
+ code: `import os
+
+from posthog import Posthog
+
+posthog = Posthog(
+ "${projectToken}",
+ host="${host}",${appHost ? `\n app_host="${appHost}",` : ''}
+ secret_key=os.environ["POSTHOG_PROJECT_SECRET_API_KEY"],
+)
+
+result = posthog.emails.send(
+ template_id="${templateId}",
+ template_data={${dataEntries(': ')}},
+ distinct_id="jane-distinct-id",
+ idempotency_key="password-reset-123",
+)
+print(result.id)`,
+ },
+ api: {
+ language: Language.Bash,
+ code: `curl -X POST ${window.location.origin}/api/projects/${currentTeamIdStrict}/messaging/send/email/ \\
-H "Authorization: Bearer $POSTHOG_PROJECT_SECRET_API_KEY" \\
-H "Content-Type: application/json" \\
-H "Idempotency-Key: password-reset-123" \\
-d '{
- "template": { "id": "${templateId}" },
+ "template_id": "${templateId}",
- "identifiers": { "distinct_id": "jane-distinct-id" },
- "message_data": ${messageData}
- }'`
+ "distinct_id": "jane-distinct-id",
+ "message_data": { ${dataEntries(': ')} }
+ }'`,
+ },
+ }
+ const snippet = snippets[language]
+ const installCommand = INSTALL_COMMANDS[language]
return (
<div className="flex flex-col gap-4 max-w-200" data-attr="transactional-email-api-example">
@@ -39,22 +118,35 @@ export function TransactionalEmailApiExample({
<li>
Authenticate with a{' '}
<Link to={urls.settings('environment-secret-api-keys')}>project secret API key</Link> that has the{' '}
- <code>hog_flow:write</code> scope.
+ <code>hog_flow:write</code> scope. Keep it on your server in{' '}
+ <code>POSTHOG_PROJECT_SECRET_API_KEY</code>.
</li>
<li>
- <code>message_data</code> fills the template's <code>{'{{ variables.* }}'}</code> placeholders. The
- template can't read person properties, so pass everything it needs here.
+ The template data fills the template's <code>{'{{ variables.* }}'}</code> placeholders. The template
+ can't read person properties, so pass everything it needs here.
</li>
<li>
- <code>identifiers.distinct_id</code> is the person the send is recorded against. Leave it out and
- the recipient's email address is used.
+ The distinct ID is the person the send is recorded against. Leave it out and the recipient's email
+ address is used.
</li>
<li>
- <code>Idempotency-Key</code> makes a retry safe. A send with the same key within 24 hours returns
- the first send's message ID instead of sending the email again.
+ The idempotency key makes a retry safe. A send with the same key within 24 hours returns the first
+ send's message ID instead of sending the email again.
</li>
</ul>
- <CodeSnippet language={Language.Bash}>{snippet}</CodeSnippet>
+ <LemonSegmentedButton size="small" value={language} onChange={setLanguage} options={LANGUAGE_OPTIONS} />
+ {installCommand ? (
+ <CodeSnippet language={Language.Bash} compact thing="install command">
+ {installCommand}
+ </CodeSnippet>
+ ) : null}
+ <CodeSnippet
+ language={snippet.language}
+ thing="code"
+ onCopy={() => posthog.capture('transactional email snippet copied', { language })}
+ >
+ {snippet.code}
+ </CodeSnippet>
</div>
)
}