> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # Send transactional emails with Go Canonical URL: https://posthog.com/docs/workflows/installation/go > **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host). ## On this page - [Install](#install) - [Set up the client](#set-up-the-client) - [Send an email](#send-an-email) - [Write automated tests](#write-automated-tests) - [Next](#next) The [Go SDK](https://posthog.com/docs/libraries/go.md) sends transactional emails. This page uses the v2 module, and every v2 release can send. On the v1 module, sending needs 1.40.0 or later. Your code sends the subject and HTML, so the email lives in your codebase. You need a [project secret API key](https://posthog.com/docs/workflows/transactional/send-from-code.md#create-an-api-key). Until you [verify your domain](https://posthog.com/docs/workflows/domain.md), emails go only to your team, from the [test sender](https://posthog.com/docs/workflows/email/test-sender.md). To see an email in your inbox first, follow the [quick start](https://posthog.com/docs/workflows/installation/quick-start.md). New to sending from code? Read [send emails from code](https://posthog.com/docs/workflows/transactional/send-from-code.md). **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 Go app with github.com/posthog/posthog-go/v2. Read https://posthog.com/docs/workflows/installation/go.md first. Follow it over anything you remember about PostHog. - Reuse the app's posthog.Client. Set SecretKey in posthog.Config from the POSTHOG_PROJECT_SECRET_API_KEY environment variable. The client then polls flag definitions with this key, so tell me that the key needs the Feature flag read scope too. - Never hard-code the secret key, log it, or put it in config that reaches the browser. - Build each IdempotencyKey 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. - Emails().Send returns (*posthog.SendEmailResult, error). Every error is a *posthog.EmailError. Read it with errors.As and branch on its Code, never on its 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 DistinctID 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 starts an httptest.Server, sets its URL as both Endpoint and AppHost in posthog.Config with AllowInsecureAppHost: true, and checks the request. Send each email's Subject and HTML from code in a posthog.CodeEmail, with a TemplateKey that names it, such as password-reset. Only send a posthog.TemplateEmail with a TemplateID if I tell you the email is a template in PostHog. Don't create the API key. I create it. ``` ## Install ```bash go get github.com/posthog/posthog-go/v2 ``` ## 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. ```go import ( "log" "os" "github.com/posthog/posthog-go/v2" ) client, err := posthog.NewWithConfig("", posthog.Config{ Endpoint: "https://us.i.posthog.com", SecretKey: os.Getenv("POSTHOG_PROJECT_SECRET_API_KEY"), }) if err != nil { log.Fatal(err) } defer client.Close() ``` When `SecretKey` is set, the client also polls flag definitions with it for [local evaluation](https://posthog.com/docs/feature-flags/local-evaluation.md). Give the key the **Feature flag** read scope too, or the client logs a failed poll each time it polls. Close the client when your app exits, not after each send. If your app sends through a reverse proxy or a self-hosted PostHog, set `AppHost` to your PostHog app URL. The client never sends email requests to a host that might be a proxy. ## Send an email ```go func sendPasswordReset(ctx context.Context, client posthog.Client, userID, email, resetLink, resetRequestID string) (string, error) { result, err := client.Emails().Send(ctx, posthog.CodeEmail{ To: email, // Names the email, so PostHog groups its sends and metrics TemplateKey: "password-reset", Subject: "Reset your password", HTML: `

Reset your password here. The link works for 1 hour.

`, DistinctID: userID, // Identifies this one email, so a retry never sends it twice IdempotencyKey: "password-reset-" + resetRequestID, }) if err != nil { // A *posthog.EmailError. Branch on its Code return "", err } return result.ID, nil } ``` `Send` returns a `*SendEmailResult` and an error. `result.ID` is the message ID. A result means PostHog queued the email, not that it delivered it. Every error is a `*posthog.EmailError`. Read it with `errors.As`, and branch on its `Code`, one of the codes in the [errors table](https://posthog.com/docs/workflows/transactional/retries-and-errors.md#what-to-retry). A wrong argument, such as a template ID that isn't a UUID, returns an `EmailError` before any request. For a longer email, render the HTML first with your template engine, such as `html/template`, and pass the result as `HTML`. See [send emails from code](https://posthog.com/docs/workflows/transactional/send-from-code.md#send-the-html) for what each field does and the checks PostHog runs. `Send` takes a `posthog.CodeEmail` for an email that your code writes, and a `posthog.TemplateEmail` for a template from PostHog. See [send emails from code](https://posthog.com/docs/workflows/transactional/send-from-code.md#send-the-html) for every field, and the [quick start](https://posthog.com/docs/workflows/installation/quick-start.md#install-an-sdk) for the version each one needs. ## Write automated tests Start an `httptest.Server` and set its URL as both `Endpoint` and `AppHost`, to see exactly what your code sends with no request to PostHog. The server uses `http`, so also set `AllowInsecureAppHost`. This tests your integration, not delivery. To test delivery, send a real email to your own address and check the [**Log**](https://posthog.com/docs/workflows/transactional.md#see-each-send) on the **Transactional** tab. ```go package email_test import ( "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/posthog/posthog-go/v2" ) func TestSendPasswordReset(t *testing.T) { keys := make(chan string, 1) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.HasSuffix(r.URL.Path, "/messaging/send/email/") { // The client also polls flag definitions here with the secret key http.NotFound(w, r) return } keys <- r.Header.Get("Idempotency-Key") w.WriteHeader(http.StatusAccepted) _, _ = w.Write([]byte(`{"message_id":"msg_1","replayed":false}`)) })) defer server.Close() client, err := posthog.NewWithConfig("phc_test", posthog.Config{ Endpoint: server.URL, AppHost: server.URL, SecretKey: "phs_test", AllowInsecureAppHost: true, // The test server uses http }) if err != nil { t.Fatal(err) } defer client.Close() result, err := client.Emails().Send(context.Background(), posthog.CodeEmail{ To: "jane@example.com", TemplateKey: "password-reset", Subject: "Reset your password", HTML: "

Reset your password.

", IdempotencyKey: "password-reset-1", }) if err != nil { t.Fatal(err) } if result.ID != "msg_1" { t.Errorf("got message ID %q", result.ID) } if key := <-keys; key != "password-reset-1" { t.Errorf("got idempotency key %q", key) } } ``` ## Next - [Attachments](https://posthog.com/docs/workflows/transactional/attachments.md), copies, and [open and click tracking](https://posthog.com/docs/workflows/transactional/sensitive-data.md) - [Link emails to your users](https://posthog.com/docs/workflows/transactional/send-from-code.md#link-emails-to-your-users) - [Send a template from PostHog](https://posthog.com/docs/workflows/transactional/templates.md), with a `posthog.TemplateEmail` with `TemplateID` and `TemplateData` - [Send from a job queue](https://posthog.com/docs/workflows/transactional/examples.md#send-from-a-job-queue), with the client's retries off - [Check an email's status](https://posthog.com/docs/workflows/transactional/status.md) - [SDK reference](https://posthog.com/docs/libraries/go.md) for every method and option