Send transactional emails with .NET

The .NET SDK sends transactional emails from version 2.20.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 .NET app with the PostHog NuGet package, or PostHog.AspNetCore for ASP.NET Core.
Read https://posthog.com/docs/workflows/installation/dotnet.md first. Follow it over anything you remember about PostHog.
- Reuse the app's PostHog client. Set SecretKey from the PostHog:SecretKey configuration value, such as user secrets or the POSTHOG_PROJECT_SECRET_API_KEY environment variable. In ASP.NET Core, inject IPostHogEmails where you send email.
- Keep the secret key in server configuration. Never commit it, and never send it to a browser or a mobile app.
- 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.
- SendAsync throws EmailException when PostHog doesn't queue the email. 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 IdentifyAsync. 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 an xUnit test that gives PostHogClient an IHttpClientFactory with a fake HttpMessageHandler and checks the request.
Send each email's Subject and Html from code in SendCodeEmailOptions, with a TemplateKey that names it, such as password-reset. Only send SendTemplateEmailOptions 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
dotnet add package PostHog

For ASP.NET Core, install PostHog.AspNetCore instead.

Set up the client

Set SecretKey on the PostHog client that your app already has. The project token keeps capturing events. The secret key sends email, so keep it in your server configuration and never ship it to a browser or a mobile app.

// Program.cs
using PostHog;
// Set PostHog:ProjectToken and PostHog:SecretKey in your configuration,
// such as user secrets or environment variables
builder.AddPostHog();
// PasswordResetService.cs: inject IPostHogEmails where you send email
using PostHog.Emails;
public class PasswordResetService(IPostHogEmails emails)
{
// ...
}

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

Dispose of 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

C#
using PostHog.Emails;
public async Task<string> SendPasswordResetAsync(User user, string resetLink, string resetRequestId)
{
// Throws EmailException when PostHog doesn't queue the email. Branch on its Code
var result = await emails.SendAsync(new SendCodeEmailOptions
{
To = user.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 = user.Id,
// Identifies this one email, so a retry never sends it twice
IdempotencyKey = $"password-reset-{resetRequestId}",
});
return result.Id;
}

SendAsync returns a SendEmailResult, and result.Id is the message ID. A result means PostHog queued the email, not that it delivered it. When PostHog doesn't queue the email, SendAsync throws an EmailException, and its Code is one of the codes in the errors table. A wrong argument throws ArgumentException before any request.

For a longer email, render the HTML first with your template engine, such as Razor, and pass the result as Html. See send emails from code for what each field does and the checks PostHog runs.

SendAsync takes SendCodeEmailOptions for an email that your code writes, and SendTemplateEmailOptions 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

PostHogClient takes an IHttpClientFactory. Give it an HttpClient with your own HttpMessageHandler 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.

C#
using System.Net;
using System.Text;
using PostHog;
using PostHog.Emails;
using Xunit;
public class PasswordResetEmailTests
{
[Fact]
public async Task SendsTheIdempotencyKey()
{
var handler = new FakeHandler();
await using var posthog = new PostHogClient(
new PostHogOptions { ProjectToken = "phc_test", SecretKey = "phs_test" },
httpClientFactory: new FakeHttpClientFactory(new HttpClient(handler)));
var result = await posthog.Emails.SendAsync(new SendCodeEmailOptions
{
To = "jane@example.com",
TemplateKey = "password-reset",
Subject = "Reset your password",
Html = "<p>Reset your password.</p>",
IdempotencyKey = "password-reset-1",
});
Assert.Equal("msg_1", result.Id);
Assert.Equal("password-reset-1", Assert.Single(handler.IdempotencyKeys));
}
}
sealed class FakeHandler : HttpMessageHandler
{
public List<string> IdempotencyKeys { get; } = [];
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IdempotencyKeys.Add(request.Headers.GetValues("Idempotency-Key").Single());
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent("""{"message_id": "msg_1", "replayed": false}""", Encoding.UTF8, "application/json"),
});
}
}
sealed class FakeHttpClientFactory(HttpClient client) : IHttpClientFactory
{
public HttpClient CreateClient(string name) => client;
}

Next

Still have questions?

Was this page useful?