> 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 .NET Canonical URL: https://posthog.com/docs/workflows/installation/dotnet > **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 [.NET SDK](https://posthog.com/docs/libraries/dotnet.md) 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](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 .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 ```bash 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. ### ASP.NET ```csharp // 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) { // ... } ``` ### Console ```csharp using PostHog; await using var posthog = new PostHogClient(new PostHogOptions { ProjectToken = "", HostUrl = new Uri("https://us.i.posthog.com"), SecretKey = Environment.GetEnvironmentVariable("POSTHOG_PROJECT_SECRET_API_KEY"), }); var emails = posthog.Emails; ``` The client loads flag definitions only when it evaluates a flag. If your app also [evaluates feature flags locally](https://posthog.com/docs/feature-flags/local-evaluation.md) 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 ```csharp using PostHog.Emails; public async Task 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 = $"

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

", 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](https://posthog.com/docs/workflows/transactional/retries-and-errors.md#what-to-retry). 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](https://posthog.com/docs/workflows/transactional/send-from-code.md#send-the-html) 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](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 `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**](https://posthog.com/docs/workflows/transactional.md#see-each-send) on the **Transactional** tab. ```csharp 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 = "

Reset your password.

", 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 IdempotencyKeys { get; } = []; protected override Task 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 - [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 `SendTemplateEmailOptions` with `TemplateId`, as a `Guid`, 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) - [Client options](https://posthog.com/docs/libraries/dotnet.md#transactional-emails) for timeouts, retries, and `app_host`