Send transactional emails with Python

The Python SDK sends transactional emails from version 7.84.0. Your code sends the subject and HTML, so the email lives in your codebase.

You need a project secret API key. Until you verify your domain, emails go only to your team, from the test sender. To see an email in your inbox first, follow the quick start. New to sending from code? Read send emails from code.

Prompt for your coding agent

Paste this into Claude Code, Cursor, or another coding agent. It sends the agent to this page and gives it the rules that agents often get wrong.

text
Add PostHog transactional email to this Python app with the posthog package.
Read https://posthog.com/docs/workflows/installation/python.md first. Follow it over anything you remember about PostHog.
- Reuse the app's Posthog or AsyncPosthog client. Add secret_key from the POSTHOG_PROJECT_SECRET_API_KEY environment variable.
- Send only from server code. Never put the secret key in code or config that reaches the browser.
- Build each idempotency_key from the record that caused the email, such as the password reset request ID or the order ID. Never use a random value or a timestamp.
- send returns a SendEmailResult and raises posthog.emails.EmailError when PostHog doesn't queue the email. Branch on error.code, never on the message.
- The SDK retries network errors and throttling for you, with the same idempotency key. Never resend the email through another email provider.
- Pass the distinct_id that the app passes to identify(). Leave it out for people without an account, such as invitees.
- Use transactional email only for email that a person needs, such as password resets, sign-in codes, and receipts. Never use it for marketing.
- Add a test that fakes HTTP: pass an httpx.AsyncClient with an httpx.MockTransport as http_client to AsyncEmails, or a requests.Session with a test adapter as session to Emails, and check the request.
Send each email's subject and HTML from code, with a template_key that names it, such as password-reset. Only send a template_id if I tell you the email is a template in PostHog. Don't create the API key. I create it.

Install

Terminal
pip install "posthog>=8,<9"

For async code, install posthog[async] instead.

Set up the client

Add your project secret API key to the PostHog client that your app already has. The project token keeps capturing events. The secret key sends email, so keep it on your server and never ship it to the browser.

import os
from posthog import Posthog
posthog = Posthog(
"<ph_project_token>",
host="https://us.i.posthog.com",
secret_key=os.environ["POSTHOG_PROJECT_SECRET_API_KEY"],
)

The client loads flag definitions only when it evaluates a flag. If your app evaluates feature flags locally with the same client, give the key the Feature flag read scope too.

In a process that only sends email, you can use Emails or AsyncEmails from posthog.emails instead of a full client.

Shut the client down when your app exits, not after each send. If your app sends through a reverse proxy or a self-hosted PostHog, set app_host to your PostHog app URL. The client never sends email requests to a host that might be a proxy.

Send an email

Python
def send_password_reset(user_id: str, email: str, reset_link: str, reset_request_id: str) -> str:
# Raises posthog.emails.EmailError when PostHog doesn't queue the email. Branch on error.code.
result = posthog.emails.send(
to=email,
# Names the email, so PostHog groups its sends and metrics
template_key="password-reset",
subject="Reset your password",
html=f'<p>Reset your password <a href="{reset_link}">here</a>. The link works for 1 hour.</p>',
distinct_id=user_id,
# Identifies this one email, so a retry never sends it twice
idempotency_key=f"password-reset-{reset_request_id}",
)
return result.id

With AsyncPosthog, await the call. send returns a SendEmailResult, and result.id is the message ID. That means PostHog queued the email, not that it delivered it. When PostHog doesn't queue the email, send raises EmailError. Branch on its code, and see what to retry. A wrong argument raises TypeError or ValueError before any request.

For a longer email, render the HTML with your template engine, such as Jinja or Django templates, and pass it as html. Fields use snake case, and from_ takes the place of from. See send emails from code for every field.

Write automated tests

Pass your own HTTP transport to see exactly what your code sends, with no network call. This tests your integration, not delivery. To test delivery, send a real email to your own address and check the Log on the Transactional tab.

Python
import httpx
from posthog.emails import AsyncEmails
requests = []
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
return httpx.Response(202, json={"message_id": "msg_1", "replayed": False})
async def test_send_password_reset():
emails = AsyncEmails(
"phs_test",
host="https://us.posthog.com",
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
)
result = await emails.send(
to="jane@example.com",
template_key="password-reset",
subject="Reset your password",
html="<p>Reset your password.</p>",
idempotency_key="password-reset-1",
)
assert result.id == "msg_1"
assert requests[0].headers["Idempotency-Key"] == "password-reset-1"

For sync code, pass a requests.Session with a test adapter to Emails(session=...). Any library that mocks requests or httpx works too.

Next

Still have questions?

Was this page useful?