Send transactional emails with Go

The Go SDK 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. 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 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

Terminal
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("<ph_project_token>", 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. 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: `<p>Reset your password <a href="` + resetLink + `">here</a>. The link works for 1 hour.</p>`,
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. 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 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 for every field, and the quick start 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 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: "<p>Reset your password.</p>",
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

Still have questions?

Was this page useful?