# ASP.NET Core

Send an ASP.NET Core app's mail with the .NET SDK, Identity's included, take a webhook's events at an endpoint that checks them, and develop against a test server.

The .NET SDK sends an ASP.NET Core app's mail through the API. Its package `Sendora.AspNetCore` also sends the mails of ASP.NET Core Identity, and takes a webhook's events at an endpoint that checks their signatures. The packages run on .NET 10 and newer. The guide ends with FluentEmail, Aspire and the tests of your app.

## Before you start

- A [server key](https://sendora.se/docs/keys), which you create on the server's **API keys** tab in the dashboard. A [test server](https://sendora.se/docs/test-servers)'s key works before Sendora approves your account, and it delivers nothing.
- A [verified sending domain](https://sendora.se/docs/domains) for the From address. A test server checks the domain too.

## Install

```sh
dotnet add package Sendora.AspNetCore
```

It brings `Sendora`, the client for the API, with it. Each package's namespace is its name. So a file that calls Identity's sender or the webhook endpoint starts with `using Sendora.AspNetCore;`, beside `using Sendora;`.

## Settings

`AddSendora()` reads the server key from the app's configuration, as `Sendora:ApiToken`. In development, keep a test server's key in user secrets, outside the project's folder:

```sh
dotnet user-secrets init
dotnet user-secrets set "Sendora:ApiToken" "sk_test_…"
```

- .NET reads user secrets only when the app runs as `Development`. In production, set the key in the environment variable `Sendora__ApiToken`, which .NET reads as `Sendora:ApiToken`. The variable `SENDORA_API_TOKEN` works too, and the setting wins over it.
- The app checks its settings as it starts. A missing key or a malformed setting stops it, with a message that names the setting and shows no value.
- Outside `Development`, a test server's key stops the app as it starts, since none of its mail would arrive. .NET runs an app as `Production` unless `ASPNETCORE_ENVIRONMENT` or `DOTNET_ENVIRONMENT` says otherwise.
- For a copy of the app that should deliver nothing, such as one on your staging server, set `Sendora:AllowTestKey` to `true`. In `Development`, a live key starts the app and logs a warning, since its mail reaches real people.

## Send mail

Register the client and a class of your own in `Program.cs`, and map an endpoint that calls the class:

```csharp
builder.Services.AddSendora(builder.Configuration);
builder.Services.AddScoped<OrderMail>();

var app = builder.Build();
app.MapPost(
    "/orders",
    async (
        Order order,
        OrderMail mail,
        CancellationToken cancellationToken
    ) =>
        Results.Ok(
            await mail.SendAsync(order, cancellationToken)
        )
);
```

The class takes the client in its constructor, as `OrderMail.cs` does:

```csharp
public sealed record Order(
    string Number,
    string Email,
    string Name
);

public sealed class OrderMail(SendoraClient sendora)
{
    public async Task<string> SendAsync(
        Order order,
        CancellationToken cancellationToken
    )
    {
        var accepted = await sendora.Email.SendAsync(
            new Email
            {
                From = new(
                    "order@example.se",
                    "Example AB"
                ),
                To = [new(order.Email, order.Name)],
                Subject = "Thank you for your order",
                Text =
                    $"Hi {order.Name}! We have received "
                    + $"order {order.Number}.",
                Tag = "order",
                Metadata = { ["orderId"] = order.Number },
                TrackOpens = false,
                TrackLinks = false,
            },
            $"order-{order.Number}",
            cancellationToken
        );
        return accepted.MessageId;
    }
}
```

- `AddSendora()` registers one `SendoraClient` for the app, which any of your classes can take. It is safe to use from many threads, and it keeps its connections between calls.
- `SendAsync()` returns the accepted message, with Sendora's `MessageId`, which the log and the webhooks use.
- Its second argument is the send's [idempotency key](https://sendora.se/docs/sending#idempotency). The SDK gives every send a key, so its own retries never send twice. Pass a key from an id of yours when the same mail may be asked for twice, as when the same order is posted twice. Sendora then sends it once, for as long as [Limits](https://sendora.se/docs/limits#requests) says it keeps the key.
- The tag sets the mail apart in the log and in every webhook, and the metadata carries ids of your own.
- `TrackOpens` and `TrackLinks` override the stream's [tracking](https://sendora.se/docs/messages#opens-and-clicks) for this mail.
- If Sendora refuses the mail, `SendAsync()` throws a `SendoraException`, whose `Code` is the [error code](https://sendora.se/docs/errors). ASP.NET Core then answers 500, as for any exception in an endpoint.

## Identity's mails

`AddSendoraIdentityEmailSender()` registers a sender for the mails of ASP.NET Core Identity. They ask a user to confirm an address, or hold a link or a code for a new password. It serves `MapIdentityApi()`, the Razor Pages UI and the Blazor Web App template.

1. In the Blazor Web App template with individual accounts, open `Program.cs`. Replace the line that registers `IdentityNoOpEmailSender` with the lines before `builder.Build()`, and add the lines after it:

```csharp
builder.Services.AddSendora(builder.Configuration);
builder.Services.AddSendoraIdentityEmailSender<
    ApplicationUser
>(options =>
    options.From = new("account@example.se", "Example AB")
);

var app = builder.Build();

// The mails take the language that the browser asks for.
app.UseRequestLocalization("en", "sv");
```

2. In `Components/Account/Pages/RegisterConfirmation.razor`, remove the `else if` block of `@code` that checks for `IdentityNoOpEmailSender`, the field `emailConfirmationLink` and the markup that shows its link. Keep the paragraph that asks the user to check their email. If the field stays, the build warns about it.

- The sender takes the place of any sender that the app registered before it.
- Without `From`, the app stops as it starts.
- The mails are in Swedish under a Swedish UI culture, and in English under any other. `UseRequestLocalization("en", "sv")` sets the culture from the language that the browser asks for, and the first, `en`, for any other.
- The mails' text names neither your app nor Sendora, and nothing in them is tracked.
- A mail waits in a queue in memory. So Identity's answer shows neither how long the API takes nor whether it refuses the mail. Either would tell whether a user has an account.
- A mail that the API refuses, or that fails after its retries, is lost, and its error code is logged as a warning.
- As the app stops, it first sends the mails that wait, for as long as the host's shutdown timeout allows.

To write a mail in your own words, derive a class from `SendoraIdentityMails<ApplicationUser>`. Override the method of that mail, `CreateConfirmationLinkMailAsync`, `CreatePasswordResetLinkMailAsync` or `CreatePasswordResetCodeMailAsync`. Each returns an `IdentityMail`, in a `ValueTask`, with its `Subject`, `Text` and `Html`. Then pass your class to `AddSendoraIdentityEmailSender` as its second type argument, after `ApplicationUser`, with the same options.

- The link and the code come as plain text, so encode them in your HTML.
- Your class is a singleton. It runs while Identity waits, and only for a user who has an account. So keep it quick, since the time that it takes tells that the account exists.

## Webhooks

`MapSendoraWebhooks()` maps an endpoint that checks each delivery's signature, then calls your handler's method for its event. A delivery is one event sent to your webhook, and each post of it is an attempt.

1. Map the endpoint in `Program.cs`:

```csharp
builder.Services.AddSendora(builder.Configuration);
builder.Services.AddSingleton<MailLog>();

var app = builder.Build();
app.MapSendoraWebhooks<MailEvents>("/webhooks/sendora");
```

2. Write the handler, a class that derives from `SendoraWebhookHandler`, such as `MailEvents.cs`. Override the method of each event that your app acts on. The others do nothing. This one keeps what each event says in the app's own log, `MailLog`, as for a bounce:

```csharp
public sealed class MailEvents(
    MailLog log,
    SendoraClient sendora
) : SendoraWebhookHandler
{
    public override Task OnBouncedAsync(
        BouncedEvent bounced,
        CancellationToken cancellationToken
    )
    {
        var outcome = bounced.Details.Hard
            ? "is undeliverable"
            : "bounced for now";
        return KeepAsync(
            bounced,
            $"{bounced.Recipient} {outcome}: "
                + bounced.Details.Classification
        );
    }
```

3. Create a webhook under the server's [Webhooks](https://app.sendora.se/servers) tab, with the endpoint's address, such as `https://example.se/webhooks/sendora`.
4. Put its secret in the setting `Sendora:WebhookSecret`, through user secrets or the environment variable `Sendora__WebhookSecret`, and deploy. An app without it stops as it starts.

The class goes on with a method for each event in the table below. `KeepAsync`, a method of its own, adds the event to `MailLog`. [Webhooks](https://sendora.se/docs/webhooks#events) says when Sendora sends each event, and [Webhook events](https://sendora.se/docs/api/webhook-events) lists their fields.

| Event                 | Class                    | Method                     |
| --------------------- | ------------------------ | -------------------------- |
| `delivered`           | `DeliveredEvent`         | `OnDeliveredAsync`         |
| `bounced`             | `BouncedEvent`           | `OnBouncedAsync`           |
| `deferred`            | `DeferredEvent`          | `OnDeferredAsync`          |
| `spam_complaint`      | `SpamComplaintEvent`     | `OnSpamComplaintAsync`     |
| `unsubscribed`        | `UnsubscribedEvent`      | `OnUnsubscribedAsync`      |
| `opened`              | `OpenedEvent`            | `OnOpenedAsync`            |
| `clicked`             | `ClickedEvent`           | `OnClickedAsync`           |
| `tracking_opted_out`  | `TrackingOptedOutEvent`  | `OnTrackingOptedOutAsync`  |
| `cap_warning`         | `CapWarningEvent`        | `OnCapWarningAsync`        |
| `cap_reached`         | `CapReachedEvent`        | `OnCapReachedAsync`        |
| `inbound`             | `InboundEvent`           | `OnInboundAsync`           |
| `inbound_cap_warning` | `InboundCapWarningEvent` | `OnInboundCapWarningAsync` |
| `inbound_cap_reached` | `InboundCapReachedEvent` | `OnInboundCapReachedAsync` |
| any other             | `UnknownEvent`           | `OnUnknownAsync`           |

- Each class derives from `WebhookEvent`, which has `Id`, `Attempt` and `Event`. The first eight also derive from `MessageEvent`, which has the message's `MessageId`, `Recipient`, `Tag` and `Metadata`.
- A missing, malformed or stale signature gets 400 before the endpoint reads the body. A body that its signature does not match gets 400 too.
- It answers 204 once your method is done. If the method throws, the app's own error handling answers, with 500 by default. Sendora then delivers the event again later, on the schedule that [Limits](https://sendora.se/docs/limits#webhooks) gives.
- Sendora waits only as long as [Limits](https://sendora.se/docs/limits#webhooks) says, so hand slow work to a queue.
- A delivery can arrive more than once. Key your handling on the event's `Id`, the delivery's id, which stays the same on each attempt. `MailLog` keeps an event once under its `Id`.
- An event newer than your release of the SDK comes to `OnUnknownAsync` as an `UnknownEvent`, so the endpoint still answers 204.
- A second webhook, such as one on another server, names the setting of its own secret, as in `app.MapSendoraWebhooks<MailEvents>("/webhooks/support", "Sendora:support:WebhookSecret")`.
- The endpoint admits anonymous callers and skips antiforgery, since the signature is its check. It stays out of the app's OpenAPI document.
- It takes the largest delivery that Sendora sends, and so does Kestrel unless your app lowers its limit. A proxy in front may take less, such as nginx with its default `client_max_body_size` of 1 MB. Raise that for the webhook's route, to the size that [Limits](https://sendora.se/docs/limits#webhooks) gives.
- To [roll the secret](https://sendora.se/docs/webhooks#roll-the-secret), create the new one, set `Sendora:WebhookSecret` to it and redeploy, since the endpoint reads the setting as the app starts. Sendora signs each delivery with both until you delete the old one.

## Received mail

The handler takes received mail too, in `OnInboundAsync`. An `inbound` event carries the mail in `Content`, unless the webhook was created with `InboundContent` set to `Reference`, as [Inbound](https://sendora.se/docs/inbound#the-inbound-event) explains. This handler downloads each attachment by its id:

```csharp
// Sendora delivers the event again if a download fails,
// or takes longer than Sendora waits for an answer.
// Hand downloads that may take so long to a queue.
public override async Task OnInboundAsync(
    InboundEvent inbound,
    CancellationToken cancellationToken
)
{
    if (inbound.AttachmentCount > 0)
    {
        await DownloadAsync(
            inbound.InboundMessageId,
            cancellationToken
        );
    }
    var content = inbound.Content;
    await KeepAsync(
        inbound,
        $"{content?.From?.Address} wrote "
            + $"\"{content?.Subject}\": {content?.Text}"
    );
}

private async Task DownloadAsync(
    string inboundMessageId,
    CancellationToken cancellationToken
)
{
    var message = await sendora.Inbound.GetAsync(
        inboundMessageId,
        cancellationToken
    );
    foreach (var attachment in message.Attachments)
    {
        var bytes =
            await sendora.Inbound.GetAttachmentAsync(
                inboundMessageId,
                attachment.AttachmentId,
                cancellationToken
            );
        var sha256 = Convert.ToHexStringLower(
            SHA256.HashData(bytes)
        );
        log.Keep(
            new(
                attachment.AttachmentId,
                "attachment",
                $"{attachment.Name}: {sha256}"
            )
        );
    }
}
```

- `Inbound.GetAsync()` reads the received message, with a description of each attachment. `Inbound.GetAttachmentAsync()` downloads one attachment's bytes.
- The sample keeps each attachment's name and SHA-256 in its log, where your app would store the file.
- Only `AuthVerdict.Pass` in `Authentication.Dmarc` means that the From domain authenticated the message. With any other verdict, the From address may be forged.
- Sendora keeps the mail's content for the stream's retention, as [Inbound](https://sendora.se/docs/inbound#what-sendora-keeps) says. After that, only the reference remains.
- A test server has no inbound stream, so receive mail on a live server.

## FluentEmail

`Sendora.FluentEmail` sends the mails of FluentEmail, in its maintained form, `jcamp.FluentEmail.Core`:

```sh
dotnet add package Sendora.FluentEmail
```

Register its sender beside the client, as this worker service does in `Program.cs`:

```csharp
builder.Services.AddSendora(builder.Configuration);
builder
    .Services.AddFluentEmail(
        "billing@example.se",
        "Example AB"
    )
    .AddSendoraSender();
builder.Services.AddSingleton<InvoiceMail>();
```

Then build each mail from `IFluentEmailFactory`, as `InvoiceMail.cs` does. Its text comes from `InvoiceText`, a class of the sample's own:

```csharp
// An IFluentEmail is one mail and keeps its recipients,
// so each invoice takes a new one from the factory.
public sealed class InvoiceMail(IFluentEmailFactory mails)
{
    public async Task<SendResponse> SendAsync(
        Invoice invoice,
        CancellationToken cancellationToken
    )
    {
        await using var pdf = File.OpenRead(invoice.Pdf);
        var attachment = new Attachment
        {
            Filename = $"invoice-{invoice.Number}.pdf",
            ContentType = "application/pdf",
            Data = pdf,
        };
        return await mails
            .Create()
            .To(invoice.Email, invoice.Name)
            .BCC("bookkeeping@example.se")
            .ReplyTo("ekonomi@example.se", "Example AB")
            .Subject($"Your invoice {invoice.Number}")
            .Body(InvoiceText.Html(invoice), isHtml: true)
            .PlaintextAlternativeBody(
                InvoiceText.Plain(invoice)
            )
            .Attach(attachment)
            .Tag("invoice")
            .Header(
                "X-Sendora-Metadata-invoiceId",
                invoice.Number
            )
            .Header("X-Sendora-Track-Opens", "false")
            .Header("X-Sendora-Track-Links", "false")
            // The app may send an invoice again, as
            // when it stops before it has marked it.
            // The key spares the customer a second mail.
            .Header(
                "X-Sendora-Idempotency-Key",
                $"invoice-{invoice.Number}"
            )
            .SendAsync(cancellationToken);
    }
}
```

- FluentEmail has no field for some of what a message can have, so headers set it, and reach no recipient. They are `X-Sendora-Stream`, `X-Sendora-Metadata-<key>`, `X-Sendora-Track-Opens` and `X-Sendora-Track-Links`.
- `X-Sendora-Idempotency-Key` sets the send's idempotency key. A send that failed may still have reached the API, as after a timeout. So give a mail that may be sent again this header, with the same value each time.
- A mail has one tag. Two different tags throw `ArgumentException`, and so does a header that Sendora writes itself, such as `DKIM-Signature`.
- If the app registers another sender before `AddSendoraSender()`, that one stays, as with FluentEmail's own senders.
- Call `SendAsync()`. `Send()`, which FluentEmail's interface requires, blocks until the API answers.

A send returns a `SendResponse`. One that the API took is `Successful`, with Sendora's id in `MessageId`. One that failed holds the [error code](https://sendora.se/docs/errors) and then its message in `ErrorMessages`, rather than throwing. A cancelled send throws. The sample's worker service logs the code:

```csharp
private async Task SendAsync(
    Invoice invoice,
    CancellationToken cancellationToken
)
{
    var response = await mail.SendAsync(
        invoice,
        cancellationToken
    );
    if (response.Successful)
    {
        invoices.MarkSent(invoice);
        logger.LogInformation(
            "Invoice {Number} is message {MessageId}.",
            invoice.Number,
            response.MessageId
        );
    }
    else
    {
        logger.LogWarning(
            "Invoice {Number} failed with {Code}.",
            invoice.Number,
            response.ErrorMessages[0]
        );
    }
}
```

To move an app from the original `FluentEmail.Core`, replace each `FluentEmail.*` package with its `jcamp.FluentEmail.*` counterpart. The namespaces stay the same.

## Aspire

An Aspire app hands the key to the project that sends, as a connection string named `sendora`. The AppHost's `AppHost.cs` declares it:

```csharp
var builder = DistributedApplication.CreateBuilder(args);

// The key of a Sendora test server, which Aspire asks for
// at the first run.
var sendora = builder.AddConnectionString("sendora");

builder
    .AddDotnetProject(
        "web",
        "../AspireApp.Web/AspireApp.Web.csproj"
    )
    .WithHttpHealthCheck("/health")
    .WithReference(sendora);

builder.Build().Run();
```

- The first run asks for the connection string's value in Aspire's dashboard or CLI. Paste the test server's key, and let Aspire save it. Aspire keeps it in `~/.aspire/secrets`, outside the repository.
- The project receives it as `ConnectionStrings__sendora`, which `AddSendora()` reads before `Sendora:ApiToken`.
- The AppHost adds the project with `AddDotnetProject`, since Aspire 17 deprecates `AddProject`.

The project that sends keeps Aspire's service defaults, and adds Sendora's health check:

```csharp
builder.AddServiceDefaults();
builder.Services.AddHealthChecks().AddSendora();
```

- The check asks the API for the key's server. The service defaults' `app.MapDefaultEndpoints()` serves it at `/health`. Through `WithHttpHealthCheck("/health")` in the AppHost, Aspire shows the project as healthy once the check passes.
- The service defaults add a handler that repeats calls through `IHttpClientFactory`. The client never sends through it, so that handler never repeats a send.

## Develop against a test server

A test server checks and logs each mail as a live server does, and delivers none of it. Its keys start with `sk_test_`.

1. Create a test server under [Servers › New server](https://app.sendora.se/servers/new), with **Test server** ticked. Copy the key that it shows you once.
2. Put the key in user secrets on your machine, as [Settings](#settings) shows. Keep a live server's key in production.
3. Send to the [simulator's addresses](https://sendora.se/docs/test-servers#the-simulators-addresses), such as `hardbounce@simulator.sendora.se`, to act out a bounce or a complaint. The message's events show in the dashboard's message log, as [Messages and events](https://sendora.se/docs/messages) explains.

Sendora posts webhooks only to a public HTTPS address, so a test server's events reach your machine only through a tunnel. To test without one, post a signed example, as the next section shows.

## Test your app

`Sendora.Testing` gives your tests a client that sends nothing, and a signed example of every webhook event. Add it to your test project alone:

```sh
dotnet add package Sendora.Testing
```

`AddSendoraFake()` puts a fake in place of each client that the app registered, so the app starts without a key. This `WebApplicationFactory` also sets the secret of each webhook:

```csharp
public sealed class App : WebApplicationFactory<Program>
{
    public const string Secret = "whsec_test";

    protected override void ConfigureWebHost(
        IWebHostBuilder builder
    ) =>
        builder
            .UseSetting("Sendora:WebhookSecret", Secret)
            .UseSetting(
                "Sendora:support:WebhookSecret",
                Secret
            )
            .ConfigureTestServices(services =>
                services.AddSendoraFake()
            );
}
```

A test class takes it as `IClassFixture<App>`. This test posts a signed bounce twice, and the app keeps it once:

```csharp
[Fact]
public async Task AnEventThatComesAgainIsKeptOnce()
{
    var body = SendoraWebhookExamples.Bounced();

    Assert.Equal(
        HttpStatusCode.NoContent,
        await PostAsync(body)
    );
    Assert.Equal(
        HttpStatusCode.NoContent,
        await PostAsync(body)
    );

    Assert.Single(EntriesOf(body));
}

private async Task<HttpStatusCode> PostAsync(
    string body,
    string secret = App.Secret
)
{
    using var client = app.CreateClient();
    using var request =
        SendoraWebhookSigner.CreateRequest(
            "/webhooks/sendora",
            body,
            secret
        );
    using var response = await client.SendAsync(
        request,
        TestContext.Current.CancellationToken
    );
    return response.StatusCode;
}
```

- `SendoraWebhookExamples` returns an example of each event, with the values that your test sets, as in `Bounced(new() { Hard = false })`. `SendoraWebhookSigner.CreateRequest()` signs it for a post to the endpoint.
- The `secret` of `PostAsync` lets a test post with a wrong secret, which gets 400.
- `EntriesOf`, a method of the test's own, reads the app's log.
- The fake records each send in `SentEmails`, `SentBatches` and `SentBroadcasts`, with its idempotency key. Take it from the app's services as `FakeSendoraClient`.
- Any other call of the fake throws `NotSupportedException`, until the test hands it a resource of its own with `Use()`.
- Identity's mails wait in a queue, which the app empties as it stops. So take the fake from the app's services, dispose the factory, and then read the fake.

## What reaches your monitoring

Sendora's packages never put an email address, a subject or a message's content in your logs, traces, metrics or error reports. No setting changes that. They record ids, statuses, timings and error codes.

- OpenTelemetry listens to them through `AddSource("Sendora")` and `AddMeter("Sendora")`.
- What can hold an address or a key of your own comes from an exception's methods, such as `GetSuppressedRecipients()`, and never from its properties. So a logger that writes an exception's properties writes none of it.
- The rule covers what the packages emit. What your own code logs, such as a whole request or event, is outside it.
