C# Web API Send Email: Build a Support Desk API in ASP.NET Core That Sends, Receives and Replies

Send email from an ASP.NET Core Web API in C#: a controller with async/await and DI, a signed webhook that receives replies, and answers in the same thread.

By · · 19 min read

An ASP.NET Core controller action in C# that sends an email with the Mailcycle .NET SDK

Searching “C# Web API send email” usually turns up a code sample that sends one message from a console app. A real ASP.NET Core Web API needs more around that call: a client registered once with dependency injection, settings that are checked when the app starts, errors that come back as proper HTTP responses, and, very often, a way to hear back when someone answers.

This tutorial builds that as a small support desk API with controllers. Opening a ticket sends the customer an email from an address made for that ticket. The customer’s answer comes back to a signed webhook endpoint in the same app, and an agent replies through the API in the same thread. Everything uses the Mailcycle .NET SDK, a C# email API client on NuGet.

If you want the basics first, two shorter posts cover them. How to send email from C# walks through HTML bodies, attachments and a background send queue in a minimal API. How to receive email in C# goes deep on the inbox: listing, attachments and waiting for a message. This post is about putting both directions into one structured Web API.

Quick answer: a C# Web API action that sends email

Inject the service that owns the client, await SendAsync, and hand it the action’s cancellation token:

[ApiController]
[Route("api/notifications")]
public sealed class NotificationsController(MailcycleConnection mailcycle) : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> Send(NotifyRequest request, CancellationToken ct)
    {
        var sent = await mailcycle.Client.Messages.SendAsync(new Outgoing(
            from: "alerts@yourdomain.com",
            to: request.Email,
            subject: "Your export is ready",
            text: "Download it from your dashboard within 24 hours."), ct);

        return Ok(new { sent.MessageId });
    }
}

public sealed record NotifyRequest(string Email);

MailcycleConnection is a ten-line class from this tutorial that connects one MailcycleClient at start-up. from must be an address on your Mailcycle account, and SendResult.MessageId is the Message-ID header the email went out with. The rest of the post builds the full API around this pattern.

Flow: an ASP.NET Core Web API opens a ticket and Mailcycle sends from the ticket address, the customer answers, and a signed webhook returns the answer to the API, which replies in the same thread
Your ASP.NET Core Web API sends from an address made for the ticket, the customer answers it, and a signed webhook brings the answer back so you can reply in the same thread.

What the support desk API does

Endpoint What happens
POST /api/tickets Creates an address for the ticket and emails the customer from it
GET /api/tickets/{id} Returns the ticket and its thread
POST /hooks/mailcycle Receives a signed message.received event and adds the customer’s email to the ticket
POST /api/tickets/{id}/replies Answers the customer’s latest email in the same thread
DELETE /api/tickets/{id} Closes the ticket and deletes its address

The design choice that makes this simple is one address per ticket. Routing replies by a ticket number in the subject breaks as soon as a customer edits it. Here the ticket’s address is the routing key: any mail that lands on it belongs to that ticket, whatever the subject says.

We built and ran this exact code against a live Mailcycle account on .NET 9 with the 0.4.0 SDK: the ticket email arrived, the customer’s answer reached the ticket’s address, a signed delivery was handled once and its retry skipped, and the threaded reply arrived with a Re: subject. The two endpoint tests at the end pass as written.

Plans and settings you need

  • .NET 8 SDK or later. The SDK package targets .NET 8; .NET 9 works too.
  • A Mailcycle account on the Scale plan, or the free 7-day Scale trial. API keys and webhooks start at Operator, and sending with an API key is a Scale feature. Scale holds 1,000 addresses and sends 250 messages a day, which suits an address per open ticket. See pricing and the rate limits.
  • An API key from API, then the Keys tab in the app. It starts with mak_ and is shown once. API keys covers what a key can do.
  • Your recovery phrase. A Mailcycle account is a 12-word phrase made on your device, with no email or password. Mail is encrypted on arrival with keys from that phrase, so the server process that opens mail and creates receiving addresses needs it alongside the key.
  • A webhook secret, which you get when you add the webhook in the receiving section.

Create the ASP.NET Core Web API project

dotnet new webapi --use-controllers -n SupportDesk
cd SupportDesk
dotnet add package Mailcycle

--use-controllers gives you a Controllers folder and AddControllers() in Program.cs. Delete the sample weather controller. The Mailcycle package brings one dependency, BouncyCastle, for the encryption that .NET lacks.

The finished project has six files of our own:

File Job
MailcycleSettings.cs The settings class, bound and checked at start-up
MailcycleConnection.cs Connects one client before the first request
Tickets.cs The ticket model and an in-memory store
SupportDesk.cs The service that sends, receives and replies
MailcycleExceptionHandler.cs Turns API refusals into ProblemDetails
Controllers/*.cs The tickets controller and the webhook controller

Bind Mailcycle settings with the options pattern

Three secrets and one display name. Put them in a class and let ASP.NET Core validate them:

using System.ComponentModel.DataAnnotations;

namespace SupportDesk;

public sealed class MailcycleSettings
{
    public const string Section = "Mailcycle";

    [Required] public string ApiKey { get; set; } = "";
    [Required] public string Phrase { get; set; } = "";
    [Required] public string WebhookSecret { get; set; } = "";
    public string FromName { get; set; } = "Support";
}

In Program.cs, ValidateOnStart() makes a missing value fail when the host starts, with a message that names the property, instead of on the first request that happens to need it:

builder.Services.AddOptions<MailcycleSettings>()
    .Bind(builder.Configuration.GetSection(MailcycleSettings.Section))
    .ValidateDataAnnotations()
    .ValidateOnStart();

Keep the API key and phrase in user secrets

In development, user secrets keep all three values out of appsettings.json and out of source control:

dotnet user-secrets init
dotnet user-secrets set "Mailcycle:ApiKey" "mak_..."
dotnet user-secrets set "Mailcycle:Phrase" "your twelve words ..."
dotnet user-secrets set "Mailcycle:WebhookSecret" "whsec_..."
dotnet user-secrets set "Mailcycle:FromName" "Acme Support"

In production, use environment variables with a double underscore (Mailcycle__ApiKey) or your platform’s secret store, such as Azure Key Vault. The phrase deserves the most care of the three: it is the account. An API key can be revoked and replaced in the app; the phrase cannot.

Register one MailcycleClient with dependency injection

The client is made by an async factory, MailcycleClient.WithApiKeyAsync(apiKey, phrase), because with a phrase it checks that the phrase belongs to the key’s account before it returns. Constructors cannot await, so we connect it in a hosted service:

using Mailcycle;
using Microsoft.Extensions.Options;

namespace SupportDesk;

public sealed class MailcycleConnection(IOptions<MailcycleSettings> options) : IHostedService, IDisposable
{
    private MailcycleClient? client;

    public MailcycleClient Client =>
        client ?? throw new InvalidOperationException("The Mailcycle client is not connected yet.");

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var settings = options.Value;
        // The key signs requests; the phrase opens mail and makes receiving addresses.
        client = await MailcycleClient.WithApiKeyAsync(
            settings.ApiKey, settings.Phrase, cancellationToken: cancellationToken);
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

    public void Dispose() => client?.Dispose();
}

Then register it twice, once as itself and once as a hosted service, so both registrations share one instance:

using SupportDesk;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOptions<MailcycleSettings>()
    .Bind(builder.Configuration.GetSection(MailcycleSettings.Section))
    .ValidateDataAnnotations()
    .ValidateOnStart();

// One Mailcycle client for the whole app, connected before the first request.
builder.Services.AddSingleton<MailcycleConnection>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<MailcycleConnection>());

builder.Services.AddSingleton<TicketStore>();
builder.Services.AddScoped<ISupportDesk, MailcycleSupportDesk>();

builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<MailcycleExceptionHandler>();

var app = builder.Build();

app.UseExceptionHandler();
app.MapControllers();

app.Run();

public partial class Program;

Why a hosted service and not a top-level await

You can also await the factory at the top of Program.cs and register the result, which is what the shorter tutorials do. The hosted service earns its extra lines in a Web API for three reasons:

  • Start-up order. Hosted services start before Kestrel accepts connections, so no request ever sees a half-made client. A revoked key or a phrase from another account fails StartAsync, and the app exits with the SDK’s message instead of serving errors.
  • Options instead of raw configuration. The connection reads the validated MailcycleSettings, so the settings rules live in one place.
  • Tests can switch it off. The integration tests later remove hosted services and swap in a fake, so the app starts without a network call.

The container owns MailcycleConnection, so it calls Dispose on shutdown and the client’s HttpClient closes with the app. The final public partial class Program; line is there for WebApplicationFactory<Program> in the tests.

Send email from an ASP.NET Core controller with async/await

The controllers depend on an interface, not on the SDK, which keeps them thin and testable:

public interface ISupportDesk
{
    Task<Ticket> OpenAsync(string customer, string subject, string question, CancellationToken ct);
    Task ReceiveAsync(string messageId, CancellationToken ct);
    Task<SendResult> ReplyAsync(Ticket ticket, string text, CancellationToken ct);
    Task CloseAsync(Ticket ticket, CancellationToken ct);
}

The ticket model and store are deliberately small. ConcurrentDictionary stands in for a database table; the lookups it offers (by ticket id, by address id, and “have we seen this event id”) are the three queries a real schema needs.

Tickets.cs in full:

using System.Collections.Concurrent;

namespace SupportDesk;

public sealed record TicketEntry(string MessageId, string Direction, string From, string Text, DateTimeOffset At);

public sealed class Ticket
{
    public required string Id { get; init; }
    public required string AddressId { get; init; }
    public required string Address { get; init; }
    public required string Customer { get; init; }
    public required string Subject { get; init; }
    public List<TicketEntry> Thread { get; } = [];
    public string? LastInboundId { get; set; }
}

// In memory for the tutorial. Use a database table in production.
public sealed class TicketStore
{
    private readonly ConcurrentDictionary<string, Ticket> byId = new();
    private readonly ConcurrentDictionary<string, string> byAddress = new();
    private readonly ConcurrentDictionary<string, byte> handledEvents = new();

    public void Add(Ticket ticket)
    {
        byId[ticket.Id] = ticket;
        byAddress[ticket.AddressId] = ticket.Id;
    }

    public Ticket? Find(string id) => byId.GetValueOrDefault(id);

    public Ticket? FindByAddress(string addressId) =>
        byAddress.TryGetValue(addressId, out var id) ? Find(id) : null;

    public void Remove(Ticket ticket)
    {
        byId.TryRemove(ticket.Id, out _);
        byAddress.TryRemove(ticket.AddressId, out _);
    }

    // True the first time an event id is seen, false on every retry.
    public bool FirstDelivery(string eventId) => handledEvents.TryAdd(eventId, 0);
}

The SupportDesk.cs class and its constructor

SupportDesk.cs holds the ISupportDesk interface above and the class that implements it. The primary constructor takes the shared connection, the store, the settings and a logger, and Mc is a short name for the connected client:

using Mailcycle;
using Microsoft.Extensions.Options;

namespace SupportDesk;

public sealed class MailcycleSupportDesk(
    MailcycleConnection connection,
    TicketStore store,
    IOptions<MailcycleSettings> options,
    ILogger<MailcycleSupportDesk> log) : ISupportDesk
{
    private MailcycleClient Mc => connection.Client;

    // OpenAsync, ReceiveAsync, ReplyAsync and CloseAsync follow.
}

The four methods below go inside that class.

One address per ticket, created when the ticket opens

OpenAsync creates the ticket’s address, stores the ticket, and sends the first email from that address:

public async Task<Ticket> OpenAsync(string customer, string subject, string question, CancellationToken ct)
{
    var id = Random.Shared.Next(10_000, 99_999).ToString();

    // Every ticket gets its own address, so a reply finds its ticket by address.
    var address = await Mc.Addresses.CreateAsync(new NewAddress
    {
        Prefix = "ticket",
        Label = $"Ticket {id}",
        RetentionDays = 30,
    }, ct);

    var ticket = new Ticket
    {
        Id = id,
        AddressId = address.Id,
        Address = address.EmailAddress,
        Customer = customer,
        Subject = subject,
    };
    store.Add(ticket);

    var sent = await Mc.Messages.SendAsync(new Outgoing(
        from: address.EmailAddress,
        to: customer,
        subject: $"[#{id}] {subject}",
        text: $"Thanks, we have your request.\n\nYou wrote:\n{question}\n\nReply to this email to add to ticket {id}.")
    {
        FromName = options.Value.FromName,
    }, ct);

    ticket.Thread.Add(new TicketEntry(sent.SentCopyId ?? sent.MessageId, "out", address.EmailAddress, question, DateTimeOffset.UtcNow));
    return ticket;
}

Some details:

  • Prefix = "ticket" gives an address like ticket- plus a random ending on a shared domain. On Scale you can use your own domain instead, so customers see ticket-...@support.yourcompany.com.
  • Label is encrypted on your machine before it is stored, so the ticket number in it stays private to your account.
  • RetentionDays = 30 keeps the thread readable for a month. Any value from 1 to 90 works; see Email addresses.
  • FromName puts “Acme Support” in the customer’s inbox in place of the bare address.
  • SentCopyId is the id of the copy kept in the address’s Sent folder. The ticket thread stores it so the history points at real messages.

The tickets controller

public sealed record OpenTicket(string CustomerEmail, string Subject, string Question);
public sealed record ReplyRequest(string Text);

[ApiController]
[Route("api/tickets")]
public sealed class TicketsController(ISupportDesk desk, TicketStore store) : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> Open(OpenTicket request, CancellationToken ct)
    {
        var ticket = await desk.OpenAsync(request.CustomerEmail, request.Subject, request.Question, ct);
        return CreatedAtAction(nameof(Get), new { id = ticket.Id }, ticket);
    }

    [HttpGet("{id}")]
    public IActionResult Get(string id) =>
        store.Find(id) is { } ticket ? Ok(ticket) : NotFound();

    [HttpPost("{id}/replies")]
    public async Task<IActionResult> Reply(string id, ReplyRequest request, CancellationToken ct)
    {
        if (store.Find(id) is not { } ticket) return NotFound();
        if (ticket.LastInboundId is null) return Conflict(new { error = "No reply from the customer yet." });

        var sent = await desk.ReplyAsync(ticket, request.Text, ct);
        return Ok(new { sent.MessageId });
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Close(string id, CancellationToken ct)
    {
        if (store.Find(id) is not { } ticket) return NotFound();
        await desk.CloseAsync(ticket, ct);
        return NoContent();
    }
}

[ApiController] gives you model binding from JSON and an automatic 400 for a malformed body. The CancellationToken parameter is bound to HttpContext.RequestAborted, so when a caller disconnects, the pending SendAsync stops with it. CreatedAtAction returns 201 with a Location header pointing at the new ticket, which is what a REST client expects from a create.

Try it with dotnet run and the port it prints:

curl -X POST http://localhost:5000/api/tickets \
  -H "Content-Type: application/json" \
  -d '{"customerEmail":"you@example.com","subject":"Export fails on large files","question":"The CSV export stops at 10 MB."}'

In our run the response was 201 Created with Location: /api/tickets/97042, and the customer’s inbox showed “[#97042] Export fails on large files” from “Acme Support” a few seconds later.

Turn Mailcycle errors into ProblemDetails

When the API refuses a call, the SDK throws ApiException with the HTTP Status, a stable Code such as rate_limited or not_your_address, the ApiMessage, and for plan refusals an UpgradeUrl. ASP.NET Core 8 added IExceptionHandler, which is the clean place to map that into an RFC 7807 response once for every controller:

using Mailcycle;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace SupportDesk;

public sealed class MailcycleExceptionHandler(IProblemDetailsService problems) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct)
    {
        if (exception is not ApiException error)
        {
            return false;
        }

        http.Response.StatusCode = error.Status switch
        {
            0 => StatusCodes.Status502BadGateway,         // no answer from the API
            429 => StatusCodes.Status429TooManyRequests,  // a sending limit: try later
            >= 500 => StatusCodes.Status502BadGateway,
            _ => StatusCodes.Status422UnprocessableEntity, // the request was refused
        };

        var details = new ProblemDetails
        {
            Title = "The email could not be sent",
            Detail = error.ApiMessage,
            Status = http.Response.StatusCode,
        };
        details.Extensions["code"] = error.Code;
        if (error.UpgradeUrl is not null)
        {
            details.Extensions["upgradeUrl"] = error.UpgradeUrl;
        }

        return await problems.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = http,
            ProblemDetails = details,
            Exception = exception,
        });
    }
}

The mapping is a choice, and this one keeps your own API honest about whose fault a failure is. A refusal for the request’s content becomes 422, because your caller sent something your email provider would not accept. A missing answer or a server error becomes 502, because the upstream failed. A sending limit stays 429, so a well-behaved client backs off. Every response keeps the SDK’s code, which your front end can switch on. The full list of codes is in the errors reference.

Exceptions that are not ApiException fall through (return false) to the default handler, so your own bugs still show up as 500 with the usual logging.

Receive email with a signed webhook endpoint in the same app

When the customer answers, Mailcycle posts a message.received event to your URL. The event carries ids, not content:

{
  "id": "evt_4k2m9x7q1b8c3v6n0z5a",
  "type": "message.received",
  "createdAt": "2026-11-29T09:14:03.000Z",
  "payload": { "messageId": "msg_91be02c4a7d1", "inboxId": "ibx_k3v9x2mq7a" }
}

Your app fetches the message by id and opens it in its own process with the phrase. That keeps the request small and the phrase on your server. The webhooks guide lists every event type.

Read the raw body in a controller action

Signature checks must run on the exact bytes that were signed. In a controller that means two rules: do not declare a [FromBody] parameter, and copy Request.Body yourself before parsing:

using System.Text.Json;
using Mailcycle;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace SupportDesk.Controllers;

[ApiController]
[Route("hooks/mailcycle")]
public sealed class MailcycleWebhookController(
    ISupportDesk desk,
    TicketStore store,
    IOptions<MailcycleSettings> options) : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> Receive(
        [FromHeader(Name = "Mailcycle-Signature")] string? signature,
        [FromHeader(Name = "Mailcycle-Event-Id")] string? eventId,
        CancellationToken ct)
    {
        // The exact bytes that were signed, read before anything parses them.
        using var buffer = new MemoryStream();
        await Request.Body.CopyToAsync(buffer, ct);
        var raw = buffer.ToArray();

        if (!WebhookSignature.VerifyNow(options.Value.WebhookSecret, raw, signature))
        {
            return Unauthorized();
        }

        if (eventId is not null && !store.FirstDelivery(eventId))
        {
            return NoContent(); // a retry of an event already handled
        }

        using var json = JsonDocument.Parse(raw);
        var root = json.RootElement;
        if (root.GetProperty("type").GetString() == "message.received")
        {
            var messageId = root.GetProperty("payload").GetProperty("messageId").GetString()!;
            await desk.ReceiveAsync(messageId, ct);
        }

        return NoContent();
    }
}

[FromHeader] binds the two headers without touching the body. WebhookSignature.VerifyNow takes the byte[] overload here, so there is no question of text encoding. It computes an HMAC-SHA256 over the timestamp and the body with your whsec_ secret, compares in constant time, and rejects a timestamp more than five minutes from now, which stops an attacker replaying an old captured delivery.

Deduplicate retries on the event id

A delivery that fails, or that your server answers slowly, is tried again: after 1 minute, then 5, then 30, and onward for about a day and a half. The Mailcycle-Event-Id header is the same on every attempt. TicketStore.FirstDelivery is a TryAdd on a concurrent set, which returns true once per id:

public bool FirstDelivery(string eventId) => handledEvents.TryAdd(eventId, 0);

With more than one instance behind a load balancer, move this to your database: insert the event id into a table with a unique key, and treat a duplicate-key error as “already handled”. Answer within 10 seconds either way. ReceiveAsync makes one fetch and one update, which fits easily; anything slower, such as calling a model to draft an answer, belongs on a queue after you return 204.

Match the email to its ticket

ReceiveAsync fetches the message and finds its ticket by the address it arrived at:

public async Task ReceiveAsync(string messageId, CancellationToken ct)
{
    var message = await Mc.Messages.GetAsync(messageId, ct);
    var ticket = store.FindByAddress(message.AddressId);
    if (ticket is null || !message.Opened)
    {
        log.LogWarning("Message {Id} has no open ticket", messageId);
        return;
    }

    ticket.Thread.Add(new TicketEntry(message.Id, "in", message.FromAddress, message.Text, DateTimeOffset.UtcNow));
    ticket.LastInboundId = message.Id;
    await Mc.Messages.MarkReadAsync(message.Id, cancellationToken: ct);
}

No subject parsing, no regular expressions on [#97042]. message.Text is the plain-text body, which is what you store or show to an agent. For HTML, use message.SafeHtml, which has trackers and remote images taken out. Opened is false only for a message that could not be decrypted. Start-up already checked the phrase against the key’s account, so that should not happen here, and the check keeps one odd message from breaking the handler.

Register the webhook for message.received

Add the webhook in the app under API, on the Webhooks tab, with your public URL ending in /hooks/mailcycle and the message.received event. Copy the whsec_ secret it shows into Mailcycle:WebhookSecret. Adding a webhook needs a signed-in session rather than an API key, so the app is the simplest place to do it. The URL must be HTTPS; for local development, put a tunnel such as Cloudflare Tunnel or ngrok in front of dotnet run.

For more on webhook payloads and retries outside .NET, see Receive email with a webhook.

Reply to an email in C# in the same thread

The reply endpoint fetches the customer’s latest email and answers it:

public async Task<SendResult> ReplyAsync(Ticket ticket, string text, CancellationToken ct)
{
    if (ticket.LastInboundId is null)
    {
        throw new InvalidOperationException("The customer has not written back yet.");
    }

    var original = await Mc.Messages.GetAsync(ticket.LastInboundId, ct);
    var to = string.IsNullOrEmpty(original.ReplyTo) ? original.FromAddress : original.ReplyTo;
    var subject = original.Subject.StartsWith("Re:", StringComparison.OrdinalIgnoreCase)
        ? original.Subject
        : $"Re: {original.Subject}";

    var sent = await Mc.Messages.SendAsync(new Outgoing(ticket.Address, to, subject, text)
    {
        FromName = options.Value.FromName,
        ReplyTo = original, // sets In-Reply-To, so mail apps keep one thread
    }, ct);

    ticket.Thread.Add(new TicketEntry(sent.SentCopyId ?? sent.MessageId, "out", ticket.Address, text, DateTimeOffset.UtcNow));
    return sent;
}

Three things make a C# reply to an email land where the customer expects it:

  1. ReplyTo = original. The SDK sends the original’s Mailcycle id and its Message-ID header. The outgoing mail carries In-Reply-To and References, which Gmail, Outlook and Apple Mail use to stack the messages into one conversation.
  2. The right recipient. original.ReplyTo holds the Reply-To header when the sender set one, and the From address otherwise. Sending there respects a customer who writes from one address and reads at another.
  3. A stable subject. Adding Re: only once keeps the subject from growing “Re: Re: Re:” over a long ticket.

The reply goes out from the ticket’s own address, so the customer’s next answer comes back to it and the webhook files it under the same ticket. The loop closes without any state in the email itself. The sending mail guide documents inReplyTo and inReplyToHeader for the raw API.

Test the webhook endpoint with WebApplicationFactory

The webhook is the part most worth an automated test, because a broken signature check fails silently: every delivery gets 401 and nothing arrives. WebhookSignature.Header exists so a test can produce a delivery Mailcycle would accept. Add a test project:

dotnet new xunit -n SupportDesk.Tests
dotnet add SupportDesk.Tests package Microsoft.AspNetCore.Mvc.Testing
dotnet add SupportDesk.Tests reference SupportDesk

Then the tests, with a fake desk that records what it receives:

using System.Net;
using System.Text;
using Mailcycle;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using SupportDesk;
using Xunit;

public sealed class FakeDesk : ISupportDesk
{
    public List<string> Received { get; } = [];
    public Task<Ticket> OpenAsync(string c, string s, string q, CancellationToken ct) => throw new NotImplementedException();
    public Task ReceiveAsync(string messageId, CancellationToken ct) { Received.Add(messageId); return Task.CompletedTask; }
    public Task<SendResult> ReplyAsync(Ticket t, string text, CancellationToken ct) => throw new NotImplementedException();
    public Task CloseAsync(Ticket t, CancellationToken ct) => Task.CompletedTask;
}

public sealed class WebhookTests : IClassFixture<WebApplicationFactory<Program>>
{
    private const string Secret = "whsec_test_only";
    private const string Received =
        """{"id":"evt_1","type":"message.received","createdAt":"2026-11-29T10:00:00.000Z","payload":{"messageId":"msg_abc","inboxId":"ibx_1"}}""";

    private readonly FakeDesk desk = new();
    private readonly HttpClient http;

    public WebhookTests(WebApplicationFactory<Program> factory)
    {
        http = factory.WithWebHostBuilder(web =>
        {
            web.UseSetting("Mailcycle:ApiKey", "mak_unused");
            web.UseSetting("Mailcycle:Phrase", "unused");
            web.UseSetting("Mailcycle:WebhookSecret", Secret);
            web.ConfigureServices(services =>
            {
                services.RemoveAll<IHostedService>(); // no connection to the API in tests
                services.AddSingleton<ISupportDesk>(desk);
            });
        }).CreateClient();
    }

    private static HttpRequestMessage Delivery(string body, string eventId, string? secret = Secret)
    {
        var bytes = Encoding.UTF8.GetBytes(body);
        var request = new HttpRequestMessage(HttpMethod.Post, "/hooks/mailcycle") { Content = new ByteArrayContent(bytes) };
        request.Content.Headers.ContentType = new("application/json");
        request.Headers.Add("Mailcycle-Event-Id", eventId);
        if (secret is not null)
        {
            var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            request.Headers.Add("Mailcycle-Signature", WebhookSignature.Header(secret, bytes, now));
        }
        return request;
    }

    [Fact]
    public async Task A_signed_delivery_reaches_the_desk_once()
    {
        var first = await http.SendAsync(Delivery(Received, "evt_1"));
        var retry = await http.SendAsync(Delivery(Received, "evt_1"));

        Assert.Equal(HttpStatusCode.NoContent, first.StatusCode);
        Assert.Equal(HttpStatusCode.NoContent, retry.StatusCode);
        Assert.Equal(["msg_abc"], desk.Received);
    }

    [Fact]
    public async Task A_wrong_or_missing_signature_is_refused()
    {
        var forged = await http.SendAsync(Delivery(Received, "evt_2", secret: "whsec_someone_else"));
        var unsigned = await http.SendAsync(Delivery(Received, "evt_3", secret: null));

        Assert.Equal(HttpStatusCode.Unauthorized, forged.StatusCode);
        Assert.Equal(HttpStatusCode.Unauthorized, unsigned.StatusCode);
        Assert.Empty(desk.Received);
    }
}

dotnet test runs both in under a second, with no network. What they prove:

  • The settings path works. UseSetting feeds the same Mailcycle section the app validates, so a renamed property breaks the test, not production.
  • The signature check is wired to the raw body. If someone later adds a [FromBody] model to the action, the first test fails.
  • Retries are skipped. The same event id twice reaches the desk once.
  • Forgeries are refused. A body signed with the wrong secret, or not signed at all, gets 401 and never reaches your code.

Removing every IHostedService is fine in a test host, since the only one that matters here is the Mailcycle connection. In a larger app, remove just that registration.

Run the whole flow end to end

With the webhook registered and the app reachable over HTTPS, a full ticket goes like this. These are the results from our run:

  1. POST /api/tickets returned 201 with ticket 97042 and its new address.
  2. POST /api/tickets/97042/replies straight away returned 409, since the customer had not written yet.
  3. The customer received “[#97042] Export fails on large files” from “Acme Support”, and answered it from their mail app.
  4. The answer arrived at the ticket’s address, and the signed message.received delivery returned 204. A second delivery with the same event id also returned 204 and changed nothing.
  5. POST /api/tickets/97042/replies with the agent’s text returned 200 and the new Message-ID.
  6. The customer received “Re: [#97042] Export fails on large files”, threaded under their own answer.
  7. GET /api/tickets/97042 showed three thread entries: out, in, out.

To read the ticket’s mail from a script while you build, mc.Messages.WaitForAsync with the ticket’s AddressId returns the next message that arrives, which is handy in a smoke test for staging.

Close a ticket and clean up its address

public async Task CloseAsync(Ticket ticket, CancellationToken ct)
{
    await Mc.Addresses.DeleteAsync(ticket.AddressId, ct);
    store.Remove(ticket);
}

Deleting the address on close keeps you inside the plan’s address count and stops late mail to an old ticket. If you would rather let a closed ticket reopen when the customer writes again, keep the address and mark the ticket closed in your table instead; the next message.received then reopens it. Retention removes old mail on its own, so either way the mailbox does not pile up.

Taking the support desk API to production

The tutorial code is complete, and these are the changes a production deployment usually makes:

  • A real store. Replace TicketStore with Entity Framework Core or Dapper. Index tickets by AddressId, and give processed event ids a unique constraint.
  • A queue for slow work. If ReceiveAsync grows, for example to notify Slack or run a classifier, write the message id to a Channel<string> and process it in a BackgroundService. The background queue section of the send tutorial has a ready pattern.
  • Your own domain. On Scale, add a domain and create ticket addresses on it with Domain on NewAddress.
  • Retries on 429. Sending limits are per account per day and per hour. The ProblemDetails handler already passes 429 through, so your queue can wait and try again.
  • One key per environment. Create separate API keys for staging and production in the app, so you can revoke one without touching the other.
  • AI help on the inbox. The same addresses can be handed to an AI agent through the Mailcycle MCP server, so Claude, Cursor or any other MCP client can read the ticket mail and draft replies for a person to send.

Next steps

FAQ

How do I send email from a .NET Core Web API controller?

Inject a service that holds one MailcycleClient, then await mc.Messages.SendAsync(new Outgoing(from, to, subject, text), ct) inside the action and pass the action's CancellationToken. The client is created once at start-up by a hosted service, so the action does no set-up of its own. The tickets controller in this tutorial is a full example.

Which C# email library works with an ASP.NET Core Web API?

Any library with an async API and a client you can share works. The Mailcycle .NET SDK (dotnet add package Mailcycle) is a C# email API client that sends over HTTPS, receives mail at addresses it creates, verifies webhooks and replies in a thread, so one package covers both directions. Every method is async and takes a CancellationToken.

Should an email client be a singleton in ASP.NET Core?

Yes. MailcycleClient holds an HttpClient and is safe to share, so register it once. Because it is created with an async factory method, this tutorial wraps it in a singleton that is also an IHostedService: it connects in StartAsync, so a bad API key stops the app before it takes traffic, and the container disposes it on shutdown.

How do I send email async in C# without blocking the request?

Await SendAsync and pass HttpContext.RequestAborted, which ASP.NET Core binds to a CancellationToken parameter on your action. The call never blocks a thread. If the send is slow work you do not want inside the request, put it on a queue read by a BackgroundService and return 202 Accepted, as shown in How to send email from C#.

How do I reply to an email in C# so it stays in the same thread?

Fetch the message you are answering with mc.Messages.GetAsync(id), then send with ReplyTo = original on the Outgoing. The SDK sends the original's id and its Message-ID, so the reply carries In-Reply-To and mail apps file it under the same conversation. Send to the original's ReplyTo address, falling back to FromAddress, and prefix the subject with Re:.

How do I receive email in an ASP.NET Core Web API?

Add a webhook for message.received that points at a controller action. The action reads the raw body, checks it with WebhookSignature.VerifyNow, deduplicates on the Mailcycle-Event-Id header, then fetches the message by id with mc.Messages.GetAsync. The message arrives parsed and opened in your process, with sender, subject, text and attachments.

How do I verify a webhook signature in ASP.NET Core?

Read Request.Body into a byte array before anything parses it, then call WebhookSignature.VerifyNow(secret, rawBytes, signatureHeader). It checks an HMAC-SHA256 of the timestamp and the body in constant time and refuses deliveries more than five minutes old. Do not bind the body to a model first: a parsed and re-serialised body no longer matches the signature.

How do I test an email webhook endpoint in ASP.NET Core?

Use WebApplicationFactory<Program> from Microsoft.AspNetCore.Mvc.Testing. Replace the email service with a fake, then sign a test body with WebhookSignature.Header(secret, bytes, timestamp) and post it. Assert that a signed delivery reaches the fake once, a retry with the same event id is skipped, and a forged or unsigned delivery gets 401.

Which plan does a C# Web API need to send email with an API key?

API keys and webhooks start on the Operator plan, and sending with an API key needs Scale, which also includes 1,000 addresses, 250 sends a day and up to 10 of your own domains. See pricing and Plans and limits.