← Back to blog

ASP.NET Core Transactional Email API (2026): Send Mail with HttpClient and POST /emails

Send transactional email from ASP.NET Core with Rovela’s HTTP API: a typed HttpClient, the Options pattern for the Bearer key, Idempotency-Key, and documented error handling — no official SDK, and not a Hangfire scheduler tutorial.

Updated November 10, 2026
ASP.NET Core Transactional Email API (2026): Send Mail with HttpClient and POST /emails

ASP.NET Core already has HttpClient; transactional email should use it

An ASP.NET Core application already calls HTTP APIs with IHttpClientFactory and the Options pattern. The natural way to send transactional email — an invoice that is ready, a “your export is ready” note, a shipping update, a security alert — is the same pattern: one HTTPS POST with a Bearer key, not SmtpClient or MailKit pointed at a mailbox.

Rovela’s Email API is built for that. There is no official SDK and no NuGet package you have to pin as an official client. The base URL is https://api.rovela.dev. You authenticate with Authorization: Bearer re_… (Authentication) and queue a message with POST /emails. The response is a message id. HTTP 200 means the message was accepted and queued, not that it has already arrived (Quick Start).

This is not a Hangfire or recurring-scheduler tutorial. If you already enqueue background work, call the same typed client from that job and keep a stable Idempotency-Key. Recurring schedules are covered elsewhere. This article is everyday ASP.NET Core app mail: a typed HttpClient, Options for the key, documented error handling around the {statusCode, name, message} envelope, and a minimal API or controller that sends after a user action.

If you are still choosing between HTTP and SMTP, read Email API vs SMTP. Rovela’s SMTP is mailbox SMTP for mail apps (mx.rovela.dev:465, a device credential, send-as-self, 30 messages a minute from one client address). Programmatic volume from an ASP.NET Core process belongs on POST /emails.

An ASP.NET Core typed HttpClient registered with IHttpClientFactory posts JSON to the email API

What you need before the first ASP.NET Core send

The first-email guide and the Quick Start are the same five steps, whether your caller is curl or ASP.NET Core:

  1. Create an account. You start on the free plan, which sends real mail. There is no separate sandbox or test key.
  2. Add and verify a sending domain (a subdomain such as mail.example.com is a common choice). You cannot send from a domain you have not verified; an unverified or foreign from is refused with a 400 that names the domain. See the domain setup guide and what domain email is.
  3. Create an API key. A sending_access key can send and nothing else — the right default for production. A full_access key can also read messages and events, and manage domains, templates, and webhooks. The full key is shown once.
  4. Send with POST /emails.
  5. Confirm delivery in the dashboard, with GET /emails/:id or GET /emails/:id/events (those reads need full_access or a dashboard session), or with a webhook.

from is a string in the documented form "Acme <hello@yourdomain.com>". The address must sit on a verified sending domain. How the display name and the address work is covered in the From name guide.

At least one of html, text, or template is required. Send both html and text where you can — many clients preview the text part (HTML email API).

A typed HttpClient and the Options pattern

Keep the key on the server. Never put a Rovela key in a browser bundle, a Blazor WebAssembly app, a mobile app, or a public repository. A leaked sending_access key can send mail as your domain. Configuration (environment variables or a secret store) is the right place.

// appsettings.json (override the key with an environment variable in production)
{
  "Rovela": {
    "ApiKey": "",
    "From": "Acme <hello@mail.acme.com>",
    "BaseUrl": "https://api.rovela.dev"
  }
}
public sealed class RovelaOptions
{
    public const string SectionName = "Rovela";
    public string ApiKey { get; set; } = "";
    public string From { get; set; } = "Acme <hello@mail.acme.com>";
    public string BaseUrl { get; set; } = "https://api.rovela.dev";
}

public sealed record EmailAccepted(string Object, string Id);

public sealed class EmailsClient
{
    private readonly HttpClient _http;
    private readonly RovelaOptions _options;

    public EmailsClient(HttpClient http, IOptions<RovelaOptions> options)
    {
        _http = http;
        _options = options.Value;
    }

    public async Task<EmailAccepted> SendAsync(
        string to, string subject, string html, string text,
        string? idempotencyKey = null, string? replyTo = null,
        CancellationToken cancellationToken = default)
    {
        var payload = new Dictionary<string, object?>
        {
            ["from"] = _options.From,
            ["to"] = to,
            ["subject"] = subject,
            ["html"] = html,
            ["text"] = text,
        };
        if (!string.IsNullOrWhiteSpace(replyTo))
            payload["reply_to"] = replyTo;

        using var request = new HttpRequestMessage(HttpMethod.Post, "/emails")
        {
            Content = JsonContent.Create(payload)
        };
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _options.ApiKey);
        if (!string.IsNullOrWhiteSpace(idempotencyKey))
            request.Headers.TryAddWithoutValidation("Idempotency-Key", idempotencyKey);

        using var response = await _http.SendAsync(request, cancellationToken);
        var body = await response.Content.ReadAsStringAsync(cancellationToken);
        if (response.IsSuccessStatusCode)
            return JsonSerializer.Deserialize<EmailAccepted>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;

        JsonElement err;
        try { err = JsonSerializer.Deserialize<JsonElement>(body); }
        catch { err = default; }
        throw new EmailsException((int)response.StatusCode, err);
    }
}
// Program.cs (excerpt)
builder.Services.Configure<RovelaOptions>(builder.Configuration.GetSection(RovelaOptions.SectionName));
builder.Services.AddHttpClient<EmailsClient>((sp, client) =>
{
    var opts = sp.GetRequiredService<IOptions<RovelaOptions>>().Value;
    client.BaseAddress = new Uri(opts.BaseUrl);
    client.Timeout = TimeSpan.FromSeconds(30);
});

There is still no official SDK; this is ordinary HttpClient. IHttpClientFactory owns the handler lifetime so you do not open a new socket on every send.

The curl equivalent of the same send, matching the Emails API and the Quick Start, is:

curl -X POST https://api.rovela.dev/emails \
  -H "Authorization: Bearer $ROVELA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: export-88-ready" \
  -d '{
    "from": "Acme <hello@mail.acme.com>",
    "to": "alice@example.com",
    "subject": "Your export is ready",
    "html": "<p>Your export is ready to download.</p>",
    "text": "Your export is ready to download."
  }'

Success looks like {"object": "email", "id": "9f1c2e40-..."}. Store that id next to the export or invoice in your database. You will want it when you debug a single message.

A minimal endpoint that sends after a user action

Transactional mail is triggered by something the user did. A minimal endpoint, with an idempotency key derived from the export id so a retried HTTP request does not send two notices:

app.MapPost("/exports/{id}/email", async (string id, EmailsClient emails, ExportStore store) =>
{
    var export = await store.GetAsync(id);
    var result = await emails.SendAsync(
        export.CustomerEmail,
        "Your export is ready",
        $"<p>Your export <b>{export.Name}</b> is ready to download.</p>",
        $"Your export {export.Name} is ready to download.",
        idempotencyKey: $"export-{export.Id}-ready",
        replyTo: "Acme Support <support@acme.com>");
    await store.SaveEmailIdAsync(export.Id, result.Id);
    return Results.Ok(new { email_id = result.Id });
});

A controller action can call the same typed client. If you already use a background queue, enqueue a job that calls SendAsync with the same key — that is a one-shot background send, not a recurring Hangfire schedule.

reply_to is optional and is not a substitute for a verified from. It tells the mail client where a human reply should go (Email API Reply-To). cc and bcc are also documented; they count toward the 50-recipient transport cap and toward monthly quota, because quota is charged per recipient, not per message (Email API CC and BCC).

An Idempotency-Key may be up to 256 characters. A retry of the same request within 24 hours returns the original response instead of sending again. That is the right default for anything driven by a queue, a payment webhook, or a user double-clicking “send export.”

Do not invent a sandbox. Free-plan keys send real mail. During development, use a verified staging subdomain and recipients you control (how to test a transactional email API).

Errors you should handle in the client

Every error uses the same shape (Quick Start, Email API error handling):

{
  "statusCode": 400,
  "name": "Bad Request",
  "message": "html or text body is required"
}

Documented cases you will actually hit from an ASP.NET Core app:

  • 400 — a missing required field, an unverified or foreign from domain, a template that does not exist, a base64 attachment that does not decode, or more than 50 recipients across to, cc, and bcc.
  • 401 — missing or invalid key, or a sending_access key used to read, reschedule, or cancel a message. Reading events is a full_access (or session) operation.
  • 429 — rate limit or monthly allowance exceeded. Official examples mention Retry-After. Each entry in a batch counts individually, so a large batch can trip this partway through. Sending also stops for the rest of the calendar month if you exceed the plan allowance (Pricing).

Surface the message field in your own logs as-is. Do not invent a /logs API; delivery history lives in the dashboard and, with a full_access key, on GET /emails/:id and GET /emails/:id/events.

A 403 can appear on management endpoints when the credential is valid but lacks permission. That is a different failure from a 401, and it is documented on the authentication pages. Map EmailsException to a problem-details response in your own API if you want, still without inventing Rovela endpoints.

SmtpClient to mailbox SMTP is send-as-self and capped; ASP.NET Core app volume should POST /emails and watch delivery on a webhook

Delivery is asynchronous — do not poll from the request path

A 200 from POST /emails is not a delivery receipt. Confirm later:

  • The Emails view in the dashboard.
  • GET /emails/:id and GET /emails/:id/events with a full_access key. You are looking for email.sent followed by email.delivered, or email.bounced if the receiving server rejected it (Email delivery status API).
  • A webhook for anything in production. Verify the HMAC-SHA256 signature (webhook security). Event types include sent, delivered, delayed, bounced, complained, opened, and clicked.

Do not turn a minimal API endpoint into a polling loop against /emails/:id/events. The docs are explicit: the events endpoint is useful for debugging a single message; systematic handling belongs on a webhook.

POST /emails/batch accepts up to 100 messages, each with the same schema, processed independently. template and topic_id are rejected on the batch endpoint rather than ignored — send those through POST /emails. If you schedule with scheduled_at, reading, rescheduling, and cancelling need full_access or a dashboard session; a sending_access key can only send. The dedicated scheduled email and batch transactional email guides cover those flows in full; this article will not redo them.

Templates are available if you would rather store HTML in Rovela and send { id, variables } (Templates API, templates guide). template is mutually exclusive with html and text. You can also render Razor or a plain string on the server and pass the result as html and text.

What not to do in an ASP.NET Core codebase

Do not reach for SmtpClient (or MailKit) and point it at mx.rovela.dev for application volume. That path is for mailboxes and mail apps. A mailbox can send only as its own address, and the documented client limit is 30 messages a minute. You also lose the HTTP API’s tracking, logs, and webhooks (SMTP, Email API vs SMTP relay).

Do not create a “Rovela SDK” wrapper that invents endpoints, official clients, numeric HTTP rate (req/s) figures, a sandbox flag, or a dedicated IP. Call the documented HTTP API with HttpClient.

Do not put the key in query parameters, in frontend code, or in a committed appsettings.json that ships to git with a live secret. Create a sending_access key for the ASP.NET Core service and inject it through configuration. If you send for several customers from one organization, a key can be restricted to a single domain (Authentication, Email API for multi-tenant SaaS).

Do not treat Task.Run or a fire-and-forget background service as a substitute for idempotency. A background call that retries after a timeout still needs an Idempotency-Key. It also does not confirm delivery; only the events API or a webhook does.

A compact ASP.NET Core checklist

  1. Verify the sending domain before any production from.
  2. Store a sending_access key in configuration; construct Authorization: Bearer … on the server.
  3. Register a typed HttpClient with IHttpClientFactory and a 30-second timeout.
  4. Send both html and text. Set reply_to when a human should be able to answer.
  5. Put an Idempotency-Key on any send a queue, webhook, or double submit might repeat.
  6. Handle 400, 401, and 429 from the documented error envelope. Remember that 200 means queued.
  7. Subscribe to webhooks for delivery, bounces, and complaints; use GET /emails/:id/events only to debug a single message.
  8. Leave mailbox SMTP to people and mail apps. Leave recurring Hangfire jobs to their own guide.

Once that typed client is in place, every other ASP.NET Core endpoint can inject it the same way — receipts, shipping updates, security alerts — without growing a second email stack. That is the point of a transactional email API: one authenticated HTTP call from the application you already run.