How to Send Email from C# and an ASP.NET Core Web API
Send email from C# and an ASP.NET Core Web API with one async call. HTML, attachments, background sending, retries and replies, with no SMTP server.

To send email from C# (C sharp), you have two broad choices: talk SMTP yourself with SmtpClient or MailKit, or call an email API over HTTPS. This tutorial does the second, with an ASP.NET Core minimal API endpoint and the Mailcycle .NET SDK. It’s the short answer to “send email web API C#”: one await, no SMTP server, no port numbers and no mailbox password in your config.
We’ll go further than a single send. By the end you’ll have an ASP.NET Core Web API that sends plain text and HTML email, attaches files from an upload, sends in the background so requests stay fast, retries the failures worth retrying, and reads the replies that come back to the same address. Mailcycle stores that mail encrypted, with keys derived from your recovery phrase on your machine, and the SDK decrypts it inside your .NET process.
To read mail as well as send it, see How to receive email in C#: create an address, wait for a message, save attachments and handle a webhook.
Quick answer: send an email in C#
Install the Mailcycle NuGet package, create a client with an API key from an environment variable, and await SendAsync with an Outgoing message. The from address must be one of your Mailcycle addresses. Sending with an API key needs the Scale plan, or the free 7-day Scale trial with no card.
dotnet add package Mailcycle
using Mailcycle;
using var mc = await MailcycleClient.WithApiKeyAsync(
Environment.GetEnvironmentVariable("MAILCYCLE_API_KEY")!);
var result = await mc.Messages.SendAsync(new Outgoing(
from: "receipts@yourdomain.com",
to: "customer@example.com",
subject: "Your order has shipped",
text: "Order 1042 is on its way."));
Console.WriteLine(result.MessageId);
SendAsync returns a SendResult. MessageId is the Message-ID header the mail went out with, and SentCopyId is the id of the copy kept in the address’s Sent folder. The rest of this post builds that into a real Web API.
What you’ll build
A small ASP.NET Core Web API with these endpoints:
| Endpoint | What it does |
|---|---|
POST /api/welcome |
Sends a plain-text welcome email from JSON input |
POST /api/password-reset |
Sends an HTML email with a plain-text fallback |
POST /api/orders/{orderId}/invoice |
Emails an uploaded PDF as an attachment, with an inline logo |
POST /api/orders/{orderId}/shipped |
Queues an email and returns 202 Accepted at once |
POST /hooks/mailcycle |
Receives a signed webhook when a reply arrives |
Plus a console snippet that sends a message, waits for the customer’s reply and answers it in the same thread. That last part is where an email API that also receives mail earns its keep: transactional and notification mail, sign-in and verification flows, support replies and agent replies, all from addresses you own, with the answers landing back in the same inbox.
Prerequisites
- The .NET 8 SDK or later. Check with
dotnet --version. The package targets .NET 8, so .NET 9 works too. - A Mailcycle account on the Scale plan, or the free 7-day Scale trial. Sending with an API key is a Scale feature. The trial needs no card. See Plans and limits and pricing.
- An address to send from. Create one in the app. It can be on one of Mailcycle’s shared domains, or on your own domain, which Scale includes.
- An email account you can receive at, such as Gmail or Outlook, for testing.
Step 1: Create an account, an address and an API key
- Open app.mailcycle.email/operator/signup and create an account. There’s no email or password: the account is a 12-word recovery phrase made on your device. Save it somewhere safe, because nothing can recover the account without it.
- In Plans & Billing, choose Start free trial to get 7 days of Scale.
- Create an email address. This is the address your API will send from, and where replies will arrive.
- Open API, then the Keys tab. Name the key, choose Create key, and copy the token. It starts with
mak_and is shown once.
The quickstart walks through the same steps with cURL, and Authentication explains what a key can and can’t do. Keys don’t expire; they work until you revoke them.
Step 2: Create the project and install the C# email library
dotnet new web -n MailApi
cd MailApi
dotnet add package Mailcycle
dotnet new web gives you an empty ASP.NET Core app with a minimal API Program.cs. The Mailcycle package is on NuGet; this post uses version 0.2.0.
Now give the app its settings. ASP.NET Core reads environment variables into IConfiguration by default, so these two lines are all it needs:
export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_FROM="receipts@yourdomain.com"
On Windows PowerShell, use $env:MAILCYCLE_API_KEY = "mak_...". In development you can keep the key out of your shell history with user secrets instead, which ASP.NET Core also reads into configuration:
dotnet user-secrets init
dotnet user-secrets set "MAILCYCLE_API_KEY" "mak_..."
Send an email from an ASP.NET Core Web API endpoint
Here is the whole Program.cs for the first endpoint:
using Mailcycle;
var builder = WebApplication.CreateBuilder(args);
var apiKey = builder.Configuration["MAILCYCLE_API_KEY"]
?? throw new InvalidOperationException("Set MAILCYCLE_API_KEY.");
var fromAddress = builder.Configuration["MAILCYCLE_FROM"]
?? throw new InvalidOperationException("Set MAILCYCLE_FROM.");
// One client for the whole app. It holds an HttpClient, so share it.
var mailcycle = await MailcycleClient.WithApiKeyAsync(apiKey);
builder.Services.AddSingleton(mailcycle);
var app = builder.Build();
app.Lifetime.ApplicationStopped.Register(mailcycle.Dispose);
app.MapPost("/api/welcome", async (WelcomeRequest request, MailcycleClient mc, CancellationToken ct) =>
{
if (string.IsNullOrWhiteSpace(request.Email))
{
return Results.BadRequest(new { error = "email is required" });
}
var sent = await mc.Messages.SendAsync(new Outgoing(
from: fromAddress,
to: request.Email,
subject: "Welcome aboard",
text: $"Hi {request.Name}, thanks for signing up.")
{
FromName = "Acme Support",
}, ct);
return Results.Ok(new { sent.MessageId });
});
app.Run();
record WelcomeRequest(string Name, string Email);
A few things worth knowing about how this is put together:
One client, created once. MailcycleClient.WithApiKeyAsync is a factory method, not a constructor, because the client can do async work as it starts (with a recovery phrase it checks the phrase against the key’s account). Top-level await in Program.cs handles that before the app starts, and AddSingleton hands the same instance to every request. The client wraps an HttpClient, so creating one per request would waste connections. Because you passed the instance in yourself, the container won’t dispose it, which is what the ApplicationStopped line is for.
Outgoing takes four required values. from, to, subject and text go in the constructor; everything optional, like FromName, Html, ReplyTo and Attachments, is an init property. from must be an address on your account, and to is one recipient. To email three people, make three calls.
The CancellationToken comes free. Minimal APIs bind a CancellationToken parameter to HttpContext.RequestAborted. Passing it to SendAsync means a client that disconnects mid-request doesn’t leave your server waiting on the call.
Run it with dotnet run and post to it, using the port it prints:
curl -X POST http://localhost:5000/api/welcome \
-H "Content-Type: application/json" \
-d '{"name":"Sam","email":"you@example.com"}'
The response carries the Message-ID, and the email arrives at the address you gave. That’s the core of “C# Web API send email” done. The rest is making it pleasant to read, robust and two-way.
Send HTML email in C#
Set Html alongside Text. The plain-text body is required, and that’s a good thing: some people read mail as text, and it’s what notification previews show. C# 11’s raw string literals make the HTML readable without escaping quotes:
// At the top of Program.cs: using System.Net;
app.MapPost("/api/password-reset", async (ResetRequest request, MailcycleClient mc, CancellationToken ct) =>
{
var resetUrl = $"https://example.com/reset?token={Uri.EscapeDataString(request.Token)}";
var name = WebUtility.HtmlEncode(request.Name);
var html = $"""
<h1>Reset your password</h1>
<p>Hi {name},</p>
<p><a href="{resetUrl}">Choose a new password</a>. The link works for 30 minutes.</p>
<p>If you didn't ask for this, you can ignore this email.</p>
""";
var text = $"""
Hi {request.Name},
Choose a new password: {resetUrl}
The link works for 30 minutes.
If you didn't ask for this, you can ignore this email.
""";
await mc.Messages.SendAsync(new Outgoing(fromAddress, request.Email, "Reset your password", text)
{
Html = html,
}, ct);
return Results.NoContent();
});
record ResetRequest(string Name, string Email, string Token);
Two habits keep HTML email safe. Encode anything a user typed with WebUtility.HtmlEncode before it goes into markup, so a name like <script> arrives as text. And escape values you put into URLs with Uri.EscapeDataString. If you prefer templates, Razor views or a library such as Scriban will render the HTML string for you; the SDK only needs the finished string.
Send email with attachments in C#
Attachments are OutgoingAttachment records: a file name and a byte[], plus an optional MimeType and ContentId. The SDK base64-encodes the bytes for you. This endpoint takes an uploaded PDF and emails it, with the company logo shown inline in the HTML:
app.MapPost("/api/orders/{orderId}/invoice", async (string orderId, string email, IFormFile file, MailcycleClient mc, CancellationToken ct) =>
{
using var buffer = new MemoryStream();
await file.CopyToAsync(buffer, ct);
await mc.Messages.SendAsync(new Outgoing(fromAddress, email, $"Invoice for order {orderId}", "Your invoice is attached.")
{
Html = """<img src="cid:logo" alt="Acme" width="120"><p>Your invoice is attached.</p>""",
Attachments =
[
new OutgoingAttachment($"invoice-{orderId}.pdf", buffer.ToArray()) { MimeType = "application/pdf" },
new OutgoingAttachment("logo.png", await File.ReadAllBytesAsync("wwwroot/logo.png", ct))
{
MimeType = "image/png",
ContentId = "logo",
},
],
}, ct);
return Results.NoContent();
}).DisableAntiforgery();
Call it with a multipart upload:
curl -X POST "http://localhost:5000/api/orders/1042/invoice?email=you@example.com" \
-F "file=@invoice.pdf"
What to know:
- Inline images use
cid:. Give the attachment aContentId, and<img src="cid:logo">in the HTML shows it in place rather than as a separate file. That avoids remote images, which many mail clients block by default. - Size and type. A message can carry up to ten files, 3.5 MB between them. Program and script files, like
.exe,.jsand.ps1, are refused withattachment_blocked. The SDK refuses too many files or too many bytes before it makes the request, with the same codes the API uses. DisableAntiforgery(). Since .NET 8, minimal API endpoints that bindIFormFileexpect antiforgery tokens, which suit browser forms. For an API called by other servers, turn it off on that endpoint, as here, and authenticate the caller your usual way.
The sending mail guide lists every attachment field and the exact size rules.
Send email asynchronously with a background queue
Every SDK method is already asynchronous, so await mc.Messages.SendAsync(...) doesn’t block a thread. “C# send email async” usually means something more, though: don’t make the user’s HTTP request wait for the email at all. The idiomatic ASP.NET Core answer is a Channel<T> and a BackgroundService, with no extra packages:
// MailQueue.cs
using System.Threading.Channels;
using Mailcycle;
public sealed class MailQueue
{
private readonly Channel<Outgoing> channel = Channel.CreateBounded<Outgoing>(1000);
public ValueTask EnqueueAsync(Outgoing message, CancellationToken ct) =>
channel.Writer.WriteAsync(message, ct);
public IAsyncEnumerable<Outgoing> ReadAllAsync(CancellationToken ct) =>
channel.Reader.ReadAllAsync(ct);
}
public sealed class MailSender(MailQueue queue, MailcycleClient mc, ILogger<MailSender> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var message in queue.ReadAllAsync(stoppingToken))
{
try
{
var sent = await mc.Messages.SendWithRetryAsync(message, stoppingToken);
log.LogInformation("Sent {MessageId} to {To}", sent.MessageId, message.To);
}
catch (ApiException error)
{
log.LogError("Sending to {To} failed: {Code} {Detail}", message.To, error.Code, error.ApiMessage);
}
}
}
}
Register both, and enqueue from the endpoint:
builder.Services.AddSingleton<MailQueue>();
builder.Services.AddHostedService<MailSender>();
// ...after builder.Build():
app.MapPost("/api/orders/{orderId}/shipped", async (string orderId, ShippedRequest request, MailQueue queue, CancellationToken ct) =>
{
await queue.EnqueueAsync(new Outgoing(
fromAddress,
request.Email,
$"Order {orderId} has shipped",
$"Your order is on its way. Track it here: {request.TrackingUrl}"), ct);
return Results.Accepted();
});
record ShippedRequest(string Email, string TrackingUrl);
Because the queue hands out one message at a time, the worker sends them one after another, which keeps you comfortably inside the per-minute send rate even when a burst of orders comes in. The bounded channel makes EnqueueAsync wait, rather than use unbounded memory, if a thousand messages are ever waiting at once.
This queue lives in memory, so messages still waiting are lost if the process stops. That’s fine for “your order has shipped” in many apps. For mail that must never be lost, write it to your database in the same transaction as the order (an outbox table) and have the worker read from there.
Handle errors and retries
Everything the SDK throws derives from MailcycleException. A refused or failed request is an ApiException with three properties: Status (the HTTP status, or 0 when no answer came back), Code (the API’s stable, machine-readable code) and ApiMessage (a human sentence). Match on Code, never on the message text. A switch expression turns codes into HTTP responses for your own callers:
app.MapPost("/api/contact", async (ContactRequest request, MailcycleClient mc, CancellationToken ct) =>
{
try
{
var sent = await mc.Messages.SendAsync(
new Outgoing(fromAddress, request.Email, "We got your message", "Thanks, we'll reply within a day."), ct);
return Results.Ok(new { sent.MessageId });
}
catch (ApiException error)
{
return error.Code switch
{
"invalid_address" => Results.BadRequest(new { error = "That email address isn't valid." }),
"rate_limited" or "daily_send_limit" or "sending_paused" =>
Results.Problem("We can't send email right now. Please try again later.", statusCode: 503),
_ => Results.Problem($"Sending failed ({error.Code}).", statusCode: 502),
};
}
});
record ContactRequest(string Email);
The codes you’re most likely to meet when sending:
| Code | Status | What it means | What to do |
|---|---|---|---|
plan_required |
403 | The plan doesn’t include sending with an API key | Move to Scale, or start the trial |
not_your_address |
403 | from isn’t an address on this account |
Fix MAILCYCLE_FROM |
invalid_address |
400 | to isn’t a valid single address |
Tell the caller; don’t retry |
domain_not_sending |
409 | Sending isn’t on yet for a domain you added | Wait a few minutes after receiving goes live |
too_many_attachments, attachments_too_large, attachment_blocked |
400 / 413 | The files break the attachment rules | Send fewer or smaller files, or a link |
rate_limited |
429 | Too many requests in a short window | Back off and retry |
daily_send_limit |
429 | The plan’s mail for today is sent | Sending resumes at 00:00 UTC |
sending_paused |
503 | Sending is paused for the rest of the day | Try again after 00:00 UTC |
network_error |
0 | No answer reached your app (timeout, DNS, connection) | See the note below |
The errors reference lists every code, and rate limits explains how 429 works. The API sends a Retry-After header with a 429; ApiException gives you the status and code, so back off with a growing delay. Here’s a small extension method, in its own file, that retries the failures worth retrying, and only those. The queue’s MailSender above already calls it:
// RetryingSend.cs
using Mailcycle;
public static class RetryingSend
{
public static async Task<SendResult> SendWithRetryAsync(this Messages messages, Outgoing message, CancellationToken ct = default)
{
var delay = TimeSpan.FromSeconds(2);
for (var attempt = 1; ; attempt++)
{
try
{
return await messages.SendAsync(message, ct);
}
catch (ApiException error) when (attempt < 4 && IsWorthRetrying(error))
{
await Task.Delay(delay, ct);
delay *= 2;
}
}
}
// Busy or a failure on Mailcycle's side: worth another try after a pause.
private static bool IsWorthRetrying(ApiException error) => error.Code is
"rate_limited" or "internal" or "send_failed" or "provider_error"
or "provider_unavailable" or "storage_unavailable" or "maintenance";
}
The when filter is the important part: an exception that doesn’t match isn’t caught at all, so after the fourth attempt, or for a code like invalid_address, it propagates with its stack trace intact. If you already use Polly or Microsoft.Extensions.Resilience, the same IsWorthRetrying test drops straight into a retry pipeline.
network_error is left out on purpose. It means your app got no answer, which can happen after the request reached the server. Retrying could send the email twice. For a password reset that’s harmless; for an invoice, log it and check the address’s Sent folder before sending again. The default request timeout is 30 seconds, and MailcycleOptions changes it:
var mailcycle = await MailcycleClient.WithApiKeyAsync(apiKey, options: new MailcycleOptions
{
Timeout = TimeSpan.FromSeconds(15),
});
Reply in the same thread
To answer an email, set ReplyTo on the Outgoing to the Message you’re replying to. The SDK fills in inReplyTo (the Mailcycle message id) and inReplyToHeader (the original’s Message-ID), which is what lets mail clients such as Gmail and Outlook show your answer under the original instead of as a new conversation:
await mc.Messages.SendAsync(new Outgoing(support.EmailAddress, reply.ReplyTo, subject, "Thanks, we'll close the ticket.")
{
ReplyTo = reply, // sets inReplyTo and the In-Reply-To header
});
Note the two different ReplyTos. reply.ReplyTo on a received Message is a string: where answers should go, which is the sender’s Reply-To header if they set one, and their From address otherwise. ReplyTo on Outgoing is the message you’re answering. Using reply.ReplyTo as the recipient respects senders who route replies to a helpdesk address.
Receive and read replies in C#
Here’s the part send-only email APIs leave to you. With Mailcycle, replies to your email arrive at the address you sent from, and your C# code can read them. Opening mail needs one more thing than sending: the recovery phrase, because mail is stored sealed to keys derived from it. Pass it as the second argument, and the client derives the keys in your process. The phrase itself never leaves the machine.
export MAILCYCLE_PHRASE="twelve words ..."
This console program sends a message, waits up to ten minutes for the customer’s answer, prints it and replies in the thread:
using Mailcycle;
using var mc = await MailcycleClient.WithApiKeyAsync(
Environment.GetEnvironmentVariable("MAILCYCLE_API_KEY")!,
Environment.GetEnvironmentVariable("MAILCYCLE_PHRASE"));
var addresses = await mc.Addresses.ListAsync();
var support = addresses.Single(a => a.EmailAddress == "support@yourdomain.com");
// Take the time before sending, so a fast reply still counts.
var since = DateTimeOffset.UtcNow;
await mc.Messages.SendAsync(new Outgoing(
support.EmailAddress,
"customer@example.com",
"Did that fix it?",
"Reply to this email and let us know."));
try
{
var reply = await mc.Messages.WaitForAsync(new WaitFor
{
AddressId = support.Id,
From = "customer@example.com",
Since = since,
Timeout = TimeSpan.FromMinutes(10),
});
Console.WriteLine($"{reply.FromAddress}: {reply.Subject}");
Console.WriteLine(reply.Text);
var subject = reply.Subject.StartsWith("Re:", StringComparison.OrdinalIgnoreCase)
? reply.Subject
: $"Re: {reply.Subject}";
await mc.Messages.SendAsync(new Outgoing(support.EmailAddress, reply.ReplyTo, subject, "Thanks, we'll close the ticket.")
{
ReplyTo = reply, // sets inReplyTo and the In-Reply-To header
});
}
catch (ApiException error) when (error.Code == "timeout")
{
Console.WriteLine("No reply in ten minutes.");
}
WaitForAsync listens on Mailcycle’s event stream and returns the first matching message, already decrypted. If the stream can’t be opened it checks the address every five seconds instead, which is why AddressId is worth passing. From and Subject are case-insensitive “contains” filters. Since matters more than it looks: it counts mail received from that moment, even mail that arrived before the stream was listening, so a customer who replies within a second isn’t missed. When nothing matches in time, it throws an ApiException with Code "timeout".
The same call makes sign-in and verification flows easy to test end to end. Point your staging app’s sign-up at a Mailcycle address, then WaitForAsync(new WaitFor { AddressId = address.Id, Subject = "verification" }) and read the code out of message.Text.
To work through an inbox instead of waiting for one message, page through it:
var page = await mc.Messages.ListAsync(support.Id, limit: 20);
foreach (var message in page.Messages.Where(m => !m.Read))
{
Console.WriteLine($"{message.ReceivedAt} {message.FromAddress} {message.Subject}");
foreach (var file in message.Attachments.Where(f => f.Stored))
{
var bytes = await mc.Messages.AttachmentAsync(message, file.Index);
// The sender chose the name: keep only the file part of it.
await File.WriteAllBytesAsync(Path.Combine("inbox", Path.GetFileName(file.Filename)), bytes);
}
await mc.Messages.MarkReadAsync(message.Id);
}
page.NextCursor takes you to the next page, or use mc.Messages.AllAsync(addressId) to walk every page. Each Message has Text, Html and SafeHtml. If you show mail in a web page, render SafeHtml: it’s the HTML with remote images, stylesheets and embeds removed, the way the Mailcycle apps show it, so a tracking pixel doesn’t report back when someone opens the message. message.Blocked lists what was removed.
A message that can’t be opened (no phrase, or the wrong one) comes back with Opened set to false and empty content, rather than throwing, so one unreadable message never hides the rest of a page. See Reading mail for folders, stars and paging.
Get a webhook when a reply arrives
WaitForAsync suits scripts, tests and agents that wait for one answer. A Web API that runs all the time is better served by a webhook: Mailcycle posts a signed event to your URL when mail arrives. Webhook events carry ids, never content, so your code fetches the message and decrypts it locally. Add the webhook in the app under API, then Webhooks, choose the message.received event, and keep the whsec_ secret it shows once.
// At the top of Program.cs: using System.Text.Json.Nodes;
var webhookSecret = builder.Configuration["MAILCYCLE_WEBHOOK_SECRET"]
?? throw new InvalidOperationException("Set MAILCYCLE_WEBHOOK_SECRET.");
// ...after builder.Build():
app.MapPost("/hooks/mailcycle", async (HttpRequest request, MailcycleClient mc, ILogger<Program> log) =>
{
// Check the signature against the raw bytes, before parsing anything.
using var buffer = new MemoryStream();
await request.Body.CopyToAsync(buffer);
var body = buffer.ToArray();
var signature = request.Headers[WebhookSignature.HeaderName].ToString();
if (!WebhookSignature.VerifyNow(webhookSecret, body, signature))
{
return Results.Unauthorized();
}
var ev = JsonNode.Parse(body);
if ((string?)ev?["type"] == "message.received")
{
var messageId = (string?)ev["payload"]?["messageId"];
log.LogInformation("New mail: {MessageId}", messageId);
// Hand messageId to a background job that calls mc.Messages.GetAsync(messageId).
}
return Results.Ok();
});
The endpoint takes HttpRequest rather than a typed body on purpose. The signature is an HMAC over the exact bytes Mailcycle sent, and model binding would parse and discard them. WebhookSignature.VerifyNow checks the HMAC and refuses a timestamp more than five minutes old, which stops a captured request being replayed later. Answer quickly and do the fetching in the background, using the same queue pattern as above. The webhooks guide lists every event and how deliveries are retried.
The raw HTTP call, for comparison
The SDK is a thin layer over a JSON API. Here’s the same send with cURL:
curl https://api.mailcycle.email/messages/send \
-H "Authorization: Bearer $MAILCYCLE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"from": "receipts@yourdomain.com",
"to": "customer@example.com",
"subject": "Your order has shipped",
"text": "Order 1042 is on its way."
}'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }
And with nothing but HttpClient:
using System.Net.Http.Json;
using var http = new HttpClient { BaseAddress = new Uri("https://api.mailcycle.email") };
http.DefaultRequestHeaders.Authorization =
new("Bearer", Environment.GetEnvironmentVariable("MAILCYCLE_API_KEY"));
var response = await http.PostAsJsonAsync("/messages/send", new
{
from = "receipts@yourdomain.com",
to = "customer@example.com",
subject = "Your order has shipped",
text = "Order 1042 is on its way.",
});
response.EnsureSuccessStatusCode();
Sending works fine this way. Reading is where the SDK earns its place: received mail comes back from the API sealed, and opening it means deriving keys from the recovery phrase and decrypting each message and attachment, which the SDK does for you and checks against Mailcycle’s published test vectors. The SDK also turns attachments into base64, threading into headers and failures into typed ApiExceptions.
SMTP vs an email API in C#
For years the standard way to send email in .NET was System.Net.Mail.SmtpClient:
using System.Net;
using System.Net.Mail;
using var smtp = new SmtpClient("smtp.example.com", 587)
{
EnableSsl = true,
Credentials = new NetworkCredential("smtp-user", "smtp-password"),
};
using var mail = new MailMessage("me@example.com", "customer@example.com", "Hello", "Hi");
await smtp.SendMailAsync(mail);
It still works, but Microsoft’s documentation now says SmtpClient is not recommended for new development because it doesn’t support many modern protocols, and recommends MailKit instead. MailKit, with MimeKit for building messages, is a thorough, well-maintained SMTP, IMAP and POP3 library, and it’s the right tool when you already have a mail server or a mailbox to connect to.
Both are SMTP clients, though, so both need an SMTP server: a host, a port, a TLS mode and credentials from a provider. An email API swaps that for one HTTPS endpoint and a key. Here’s how the three compare:
SmtpClient |
MailKit / MimeKit | Mailcycle .NET SDK | |
|---|---|---|---|
| What you need | An SMTP server, port and credentials | An SMTP server, port and credentials | An API key and an address on your account |
| Transport | SMTP, STARTTLS only (no implicit TLS on 465) | SMTP with STARTTLS or implicit TLS | HTTPS, JSON |
| Async | SendMailAsync, one send at a time per instance |
Async methods; one connection per client instance | Every method async with CancellationToken; one shared client |
| HTML and attachments | MailMessage, AlternateView, Attachment |
BodyBuilder |
Html and Attachments on Outgoing |
| Reply threading | Set In-Reply-To and References headers yourself |
Set the headers yourself | ReplyTo = message |
| Receiving replies | Not supported | IMAP or POP3 against a mailbox you run | Same address; WaitForAsync, ListAsync, webhooks |
| Errors | SmtpException with an SMTP status code |
Typed exceptions with SMTP status | ApiException with a stable Code |
| Stored mail | Wherever your mail server keeps it | Wherever your mail server keeps it | Encrypted, keys derived from your phrase |
If you already run a mail server, or the job is reading a mailbox someone else hosts, MailKit is a fine choice. If you want a Web API that sends from addresses you own and reads the replies without running mail infrastructure, an email API is less to set up and less to keep secure.
Using it with AI agents
The same pattern works for an agent written in C#: give it a Mailcycle address, send with SendAsync and wait for answers with WaitForAsync. If your agent runs in an MCP client instead, such as Claude Code, Codex or Cursor, or any other MCP client, it doesn’t need C# at all. Mailcycle’s MCP server gives it its own inbox; see how to give Claude Code its own email address and the AI agents guide.
Next steps
- C# Web API send email: an ASP.NET Core support desk, for DI, a signed webhook and threaded replies in one Web API.
- Read the .NET SDK guide. The full guide covers creating addresses from code, sessions, the event stream and webhooks management.
- Send from your own domain. On Scale, add your domain and send as
receipts@yourcompany.com. - Manage keys. API keys explains how keys are created, listed and revoked.
- Compare other languages. The hub post shows how to send email from any language, with siblings for TypeScript, Python, Go and Java.
- See everything for developers. The developers page collects the SDKs, the API and the MCP server.
FAQ
How do I send an email from a C# Web API?
Create one MailcycleClient at startup with MailcycleClient.WithApiKeyAsync, register it as a singleton, and call await mc.Messages.SendAsync(new Outgoing(from, to, subject, text), ct) inside your endpoint. Pass the request's CancellationToken so a cancelled request stops the call. The full endpoint is in this tutorial.
How do I send bulk email in C#?
Loop over your recipients and call SendAsync once per person, since each call sends to one recipient, ideally from the background queue so your endpoint stays fast. Mailcycle is built for transactional mail people expect, like receipts, alerts and sign-in codes, so the plan's daily sending total applies. See Rate limits.
Is SmtpClient deprecated in .NET?
System.Net.Mail.SmtpClient isn't marked [Obsolete], but Microsoft's documentation says it is not recommended for new development because it doesn't support many modern protocols, and points to MailKit instead. It still works for simple SMTP sends if you have a server and credentials.
How do I send an email with an attachment in C#?
Add OutgoingAttachment objects to the Attachments list on Outgoing, each with a file name and a byte[], for example from File.ReadAllBytesAsync or an uploaded IFormFile. The SDK base64-encodes them for you. A message can carry up to ten files, 3.5 MB between them, and program and script files such as .exe are refused.
How do I send email asynchronously in C#?
Every Mailcycle SDK method is async and takes an optional CancellationToken, so await mc.Messages.SendAsync(...) never blocks a thread. To keep a web request fast, write the message to a Channel<Outgoing> and let a BackgroundService send it, then return 202 Accepted.
Do I need an SMTP server to send email from C#?
Not with an email API. Mailcycle sends over HTTPS with an API key, so there is no SMTP host, port, TLS mode or mailbox password to configure. With SmtpClient or MailKit you need an SMTP server and credentials from a provider.
Can I receive email in C#?
Yes. With your recovery phrase passed to the client as well as the API key, mc.Messages.WaitForAsync waits for the next matching message and returns it decrypted, and mc.Messages.ListAsync pages through an inbox. Replies land at the same address you sent from. See Reading mail.
How do I send HTML email in C#?
Set the Html property on Outgoing and keep a plain-text body in Text, which is required. Encode any user input with WebUtility.HtmlEncode before putting it in the HTML, and use cid: images with an attachment's ContentId for inline logos.
Which .NET versions does the Mailcycle SDK support?
The Mailcycle NuGet package needs .NET 8 or later, so it works in ASP.NET Core 8 and 9, worker services and console apps. Its one dependency is BouncyCastle, used for the encryption.
Can I send email from my own domain in C#?
Yes. On the Scale plan you can add up to 10 of your own domains and create addresses on them, then use one as from. See Your own domains.
Related
Send email from any language
- Send Email with an API: Code Examples in TypeScript, Python, C#, Go, Rust, PHP, Java, Ruby and Swift (Overview: every language)
- How to Send Email from Go (Golang): HTML Templates, a Mailer Package and an API (Go)
- How to Send Email from Java: A Plain Java Program, Spring Boot, HTML, Attachments and Replies (Java / Spring Boot)
- How to Send Email from PHP with an API (Laravel and Plain PHP) (PHP / Laravel)
- How to Send Email from Python with an API: Scripts, FastAPI and Django (Python)
- How to Send Email from Ruby and Rails with an Email API (Ruby / Rails)
- How to Send Email from Rust with an API: HTML, Attachments, Axum and Replies (Rust)
- How to Send Email From Swift: Vapor, iOS and Server-Side Swift (Swift / Vapor)
- How to Send Email from Node.js and TypeScript (Express and Next.js) (TypeScript / Node.js)