How to Send Emails in C# / .NET (ASP.NET Core, 2026 Guide)
Jump to section (13)
- Pick an Email Provider
- Why Not SmtpClient?
- Install Dependencies
- Create the Email Service
- Send Your First Email
- Build Email Templates
- Common Email Patterns for SaaS
- Background Sending with Channels
- Error Handling with Polly
- Testing
- Going to Production
- Beyond Transactional: Marketing Emails and Sequences
- Frequently Asked Questions
To send email from C#, use a provider's HTTP API or a maintained SMTP library. In ASP.NET Core, put that transport behind an injected service, keep credentials on the server and distinguish “accepted for processing” from “delivered.” Those decisions matter more than whether the first request uses an SDK or HttpClient.
This guide builds a complete .NET 10 example using Sequenzy's REST API and the ASP.NET Core shared framework. The example needs no provider SDK or extra NuGet package. The request and response fields follow the Send Email contract. Sequenzy is our product; Resend, SendGrid and SMTP remain valid choices when their tooling or infrastructure fits your team better.
The two C# files below were compiled on .NET 10 and exercised with a fake HTTP handler, without sending real email. That verifies the example's request construction and failure handling, not live account configuration or inbox delivery. We do not claim it was run against every .NET release or competitor SDK.
Pick an Email Provider
Start with the work your application needs to do. A receipt is one service-triggered message. A trial onboarding program also needs audience eligibility, delays, unsubscribe handling and rules for stopping after conversion. You can own those rules in your application, or choose a platform that manages them.
| Path | Useful when | What you still need to decide |
|---|---|---|
| Sequenzy REST API | Transactional messages and SaaS lifecycle campaigns should share a platform | Sending policy, templates, event model and consent |
| Resend API or .NET library | You want developer tooling and React Email templates | Template workflow, product configuration and automation requirements |
| SendGrid API or official .NET SDK | You already use its infrastructure or ecosystem | Email API versus Marketing Campaigns scope, sender setup and billing |
| SMTP with MailKit | Your organization operates an SMTP relay or requires SMTP interoperability | Authentication, connection lifecycle, retries and delivery observability |
Resend now documents Automations, including event-triggered sequences. Do not choose a different provider on the assumption that Resend cannot automate messages. Build one representative journey in the candidates and compare editing, targeting, diagnostics and cost.
For a 10,000-subscriber example, define the sends too: four newsletters plus 10,000 application messages is 50,000 messages per month. Sequenzy's current $49/month tier includes 60,000 emails. That is an allowance comparison, not a promise about inbox placement. For another vendor, price its applicable contact and message products at that workload; its smallest advertised tier may cover a different use case. Check current Sequenzy pricing, Resend pricing and SendGrid pricing before committing.
Why Not SmtpClient?
Microsoft says System.Net.Mail.SmtpClient is not recommended for new development, because it does not support many modern protocols. That is different from saying the whole class is marked [Obsolete], or that its asynchronous API does not exist. Avoid copying either inaccurate explanation into your technical decisions.
SMTP itself remains useful. If you have a company relay, an on-premise dependency or an SMTP-based integration, consider MailKit. Configure the authentication and TLS mode your relay supports. An HTTP API is convenient when you want provider-specific templates, structured responses, idempotency or delivery diagnostics; SMTP may be simpler when an existing relay already handles those operational responsibilities.
Also avoid creating a new standalone HttpClient for every message. The example below uses a typed client from IHttpClientFactory. A deliberately long-lived client with suitable connection management is another supported design; the problem is unmanaged connection lifetime, not the mere presence of new HttpClient in any program.
Install Dependencies
Create an empty ASP.NET Core project with the .NET 10 SDK:
dotnet new web -n EmailDemo --framework net10.0
cd EmailDemo
dotnet user-secrets initKeep the generated project file. Replace Program.cs with the first C# block and add SequenzyEmailSender.cs from the next section. Both files belong in the project root. The remaining smaller examples explain integration choices; they are not extra files required to start this project.
Configure Your Sender and Secrets
Add this non-secret configuration to appsettings.json, preserving any logging configuration you want:
{
"Email": {
"From": "Your App <hello@your-verified-domain.com>",
"TestRecipient": "your-own-inbox@example.com",
"TestSendId": "local-connection-check-001"
}
}Replace the sender with a verified sender identity and the recipient with an inbox you control. The test send ID identifies one logical message: repeating the test with the same ID and unchanged content should not create a new delivery. To deliberately send another test, change the ID first. If you change the content while reusing an accepted ID, expect a conflict rather than a second message.
Store the API key through User Secrets for local development:
dotnet user-secrets set "Email:ApiKey" "YOUR_SEQUENZY_API_KEY"User Secrets keeps the value out of the project file; it is not an encrypted production vault. For a deployed app, provide Email__ApiKey through your hosting secret store or an appropriate vault. Never put a sending key in a Blazor WebAssembly bundle, a browser environment variable or an example committed to a public repository. See Microsoft's secret-storage guidance.
Create the Email Service
Register in DI
Use the following complete Program.cs. The development-only route selects its recipient from server configuration; it does not accept arbitrary addresses or message bodies from a caller. Run it on loopback for local testing. This route is intentionally absent when the application environment is Production.
// Program.cs
using System.Net.Http.Headers;
using System.Net.Mail;
var builder = WebApplication.CreateBuilder(args);
var apiKey = builder.Configuration["Email:ApiKey"];
var from = builder.Configuration["Email:From"];
if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(from))
throw new InvalidOperationException("Configure Email:ApiKey and Email:From.");
_ = new MailAddress(from);
builder.Services.AddHttpClient<IEmailSender, SequenzyEmailSender>(client =>
{
client.BaseAddress = new Uri("https://api.sequenzy.com/api/v1/");
client.Timeout = TimeSpan.FromSeconds(15);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
});
builder.Services.AddSingleton(new EmailSettings(from));
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
var recipient = app.Configuration["Email:TestRecipient"];
var sendId = app.Configuration["Email:TestSendId"];
if (string.IsNullOrWhiteSpace(recipient) || string.IsNullOrWhiteSpace(sendId))
throw new InvalidOperationException("Configure the test recipient and send ID.");
_ = new MailAddress(recipient);
app.MapPost("/dev/send-test", async (IEmailSender sender, CancellationToken ct) =>
{
var message = new OutboundEmail(
recipient, "Connection test", "<p>Your email connection works.</p>", sendId);
var accepted = await sender.SendAsync(message, ct);
return Results.Accepted(value: new
{
accepted.EmailSendId,
status = "accepted_for_processing"
});
});
}
app.Run();The HTTP client configuration is centralized, so the transport can be replaced without rewriting every domain handler. Keep the recipient-selection and authorization rules in your application services. A provider adapter should not decide which customer is entitled to receive an invoice, or whether a user has consented to onboarding marketing.
Implement the Transport
The canonical Sequenzy direct-content fields are subject and body. The API also accepts html as a compatibility alias, but using one documented shape reduces ambiguity. This adapter sends one recipient per operation, treats a successful response as queue acceptance and returns the identifier you need for later diagnostics.
// SequenzyEmailSender.cs
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
public sealed record EmailSettings(string From);
public sealed record OutboundEmail(
string To, string Subject, string Html, string SendId);
public sealed record AcceptedEmail(string EmailSendId);
public interface IEmailSender
{
Task<AcceptedEmail> SendAsync(OutboundEmail email, CancellationToken ct = default);
}
public sealed class SequenzyEmailSender(
HttpClient client, EmailSettings settings) : IEmailSender
{
public async Task<AcceptedEmail> SendAsync(
OutboundEmail email, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(email.SendId) || email.SendId.Length > 255 ||
email.SendId.Any(c => c < '!' || c > '~'))
throw new ArgumentException("Use a stable, printable ASCII send ID up to 255 characters.");
using var request = new HttpRequestMessage(HttpMethod.Post, "transactional/send");
request.Headers.Add("Idempotency-Key", email.SendId);
request.Content = JsonContent.Create(new
{
from = settings.From,
to = email.To,
subject = email.Subject,
body = email.Html,
emailType = "transactional"
});
using var response = await client.SendAsync(request, ct);
if (!response.IsSuccessStatusCode)
throw new EmailSubmissionException(response.StatusCode);
SendResponse? result;
try
{
result = await response.Content.ReadFromJsonAsync<SendResponse>(ct);
}
catch (JsonException ex)
{
throw new InvalidOperationException(
"Acceptance response unreadable; reconcile using the same send ID.", ex);
}
if (result?.Success != true || string.IsNullOrWhiteSpace(result.EmailSendId))
throw new InvalidOperationException(
"Acceptance response incomplete; reconcile using the same send ID.");
return new AcceptedEmail(result.EmailSendId);
}
private sealed record SendResponse(
[property: JsonPropertyName("success")] bool Success,
[property: JsonPropertyName("emailSendId")] string? EmailSendId);
}
public sealed class EmailSubmissionException(HttpStatusCode statusCode)
: Exception($"Email submission rejected: HTTP {(int)statusCode}.")
{
public HttpStatusCode StatusCode { get; } = statusCode;
}The adapter deliberately does not catch every exception and return false. A rejected request, a network failure and an unreadable acceptance response require different investigation. It also avoids logging full request bodies or provider responses, which may contain personal information or security links. Your worker can record the stable send ID, status code, attempt time and duration without recording the message itself.
This example fixes the delivery policy to transactional. Use it for user-requested actions and service messages, such as receipts or password resets. Do not send a promotional onboarding campaign through this adapter just to bypass unsubscribe behavior. A marketing adapter should explicitly use the documented marketing policy and preserve the provider's eligibility and unsubscribe rules.
Send Your First Email
Start the local development server:
dotnet run --no-launch-profile --environment Development --urls http://127.0.0.1:5080Then, from another terminal:
curl -i -X POST http://127.0.0.1:5080/dev/send-testA successful local response is HTTP 202 with status: "accepted_for_processing" and an emailSendId. That means the provider accepted the operation for background processing. It does not mean the recipient saw it, and a downstream suppression or delivery failure is still possible. Look up that send in the dashboard or the email-send details API before diagnosing a missing message.
If the sender has not been verified, fix sender configuration rather than repeatedly submitting new message IDs. If the API key lacks permission, fix that access. If an existing send ID is reused with a different recipient or body, Sequenzy rejects the mismatch instead of treating it as a fresh delivery.
Minimal API and Controller Integration
In a production API, call IEmailSender from an authorized application workflow. For example, create the invoice, commit its outbound notification record and let a worker submit that record. Do not expose an anonymous /send-email endpoint that forwards arbitrary recipients, HTML and subjects to the provider. Even an authenticated endpoint needs company access checks, purpose-specific limits and a recipient derived from trusted state.
A controller and a minimal API route can use the same injected service. The difference is how your application organizes its HTTP boundary, not which transport it needs. Keep the domain operation responsible for deciding whether a message should exist; keep the adapter responsible for one submission. That separation makes retries and authorization tests easier to reason about.
The CancellationToken from an HTTP request is appropriate for the local demonstration. Durable background work should instead use the worker's lifetime and per-attempt timeout. Once your application has committed that an invoice notice must be sent, a user closing their browser should not discard the notification.
Build Email Templates
Option 1: Raw String Literals
C# raw strings are convenient for a short template. They do not automatically HTML-escape interpolated values. Encode user-controlled text, validate link origins and keep untrusted input out of raw markup.
using System.Net;
public static class ReceiptTemplate
{
public static string Render(string name, string invoiceNumber)
{
var safeName = WebUtility.HtmlEncode(name);
var safeInvoice = WebUtility.HtmlEncode(invoiceNumber);
return $"""
<!doctype html>
<html lang="en">
<body>
<h1>Payment received</h1>
<p>Hi {safeName},</p>
<p>We've recorded payment for invoice {safeInvoice}.</p>
<p>Open your account to view the receipt.</p>
</body>
</html>
""";
}
}This is a content-escaping example, not a complete email-client design system. Test the real message in the clients your customers use. Avoid placing untrusted values into CSS, tag names or an href merely because you encoded them as text; those contexts need their own validation. For security links, construct a URL from a trusted HTTPS application origin and the credential your authentication system issued.
Separate plain text, subject data and HTML in your template model. A user's name may be fine in an escaped paragraph but should not be allowed to inject a newline into a subject or header. Treat names as optional, and render a neutral greeting when an upstream source sends an empty or malformed value.
Option 2: Razor Templates
Razor is useful when your team already maintains typed view models and wants layout reuse. Standard Razor expressions HTML-encode values, but Html.Raw bypasses that protection. Using Razor outside an MVC request requires an explicit rendering setup; dropping a .cshtml file into the project does not by itself create a background-worker renderer.
Choose a maintained renderer or implement a rendering service that creates the required scope and view context. Test it in the same process type that sends the email. A template that renders inside a controller can still fail in a worker if it depends on an HTTP context, request culture or scoped service that is unavailable there.
For messages maintained by non-engineers, a provider-managed template can be simpler. Sequenzy's send API accepts a saved template slug plus variables instead of direct subject and body. Follow the template-send documentation. Keep its adapter separate enough that tests can verify you did not accidentally send both template and conflicting direct-content fields.
Version the Content Used by a Retry
The email your worker retries should represent the same logical operation. If rendering from “the latest template” changes the body between attempts, the provider may reject an idempotency-key mismatch. Persist the rendered payload or a template version and immutable variables when creating the job, according to your privacy and retention requirements.
Password-reset content needs an additional rule: do not retry a message containing an expired credential. The worker should detect expiry and stop or invoke your approved recovery process. It must not mint a new token in each retry without coordinating with the authentication service, because doing so can invalidate the message the user just received.
Common Email Patterns for SaaS
Stripe Webhook Handler
Payment notifications are an event-processing problem before they are an email-rendering problem. Verify the Stripe signature against the original request body, identify the business action and save the work durably before acknowledging receipt. Follow Stripe's webhook guidance for duplicate and out-of-order delivery.
Persist the provider event ID for webhook replay protection, and define a separate business uniqueness rule for the notification when several events can describe the same invoice outcome. A different Stripe event ID does not necessarily mean the user should receive another receipt. Keep the email send ID stable for that logical notification, such as a stored notification row ID.
Do not await a live email submission before returning every billing webhook response. A temporary email-provider outage should not cause your billing ingestion to fail repeatedly. Commit the authoritative state change and outbox work, acknowledge the event, then let a worker process the notification. Check current invoice state before sending delayed messages that might now be misleading.
Password Resets and Account Verification
Keep token generation, storage, expiry and consumption in your authentication system. Email delivery is the transport, not the authority deciding whether a user may reset a password. Use the password-reset templates for copy, then test expired, used and scanner-visited links in the actual authentication flow.
Disable click rewriting for recovery links where redirects would break the intended flow or expose credentials to extra systems. Sequenzy accepts per-send trackingSettings opt-outs; add them deliberately to the request DTO when your security-email adapter needs them. Do not assume a setting in the email editor covers every direct-content send.
Product Updates and Lifecycle Messages
A sequence is more than a list of scheduled API calls. It needs a current eligibility decision: should the user still receive this message after upgrading, unsubscribing or leaving the account? For B2B software, determine which organization and role the event refers to before selecting the recipient.
Sequenzy, Resend Automations and other lifecycle platforms can manage parts of that orchestration. If your app owns it, persist each step and its stop conditions. Avoid implementing a week-long delay as an in-memory Task.Delay; a deployment or process restart will not preserve that execution state.
Background Sending with Channels
A bounded Channel<T> can coordinate short-lived work inside a process and apply backpressure. It is not durable storage. When a server restarts, pending messages disappear unless you have persisted them elsewhere. Increasing the channel capacity does not change that failure mode.
For customer-facing notifications, use a durable queue or an outbox in your application database. Persist the business operation and its notification intent in the same transaction. Workers can then claim pending records, submit them and store acceptance IDs. Keep the following states distinguishable:
| State | Meaning | Next action |
|---|---|---|
| Pending | Notification exists durably but has not been submitted | Worker claims it |
| Processing | A worker holds a time-limited claim | Submit or recover an expired claim |
| Accepted | Provider returned a submission identifier | Await delivery events; do not submit a fresh message |
| Retry scheduled | Temporary failure or uncertain submission needs reconciliation | Reuse the same send ID and payload |
| Delivered or suppressed | Provider reported a downstream outcome | Record the result and apply the relevant policy |
| Failed | Permanent error or retry budget exhausted | Inspect and deliberately repair or cancel |
A worker crash after provider acceptance but before saving the result is the important edge case. Your queue will redeliver the job, so the second attempt must use the first attempt's send ID. Provider-side deduplication closes that submission gap within its documented retention period; a local “sent” boolean alone cannot.
Multiple workers also need a claim or lease mechanism. Reading all pending rows and then marking each one as processing is vulnerable to concurrent workers selecting the same row. Use your database or queue's supported atomic claiming behavior. Renew or expire leases deliberately, and ensure a stale worker cannot overwrite a newer terminal result.
Error Handling with Polly
Retries can help an unreliable network; they can also duplicate side effects. The example transport makes one attempt and lets a durable worker own retry scheduling. If you add Polly-based resilience inside the transport as well, account for the combined attempt budget so three queue attempts do not unexpectedly become dozens of provider requests.
Microsoft's HTTP resilience package provides retry controls, including disabling retries for unsafe HTTP methods. Do not attach a default retry pipeline to an email POST without verifying the provider's idempotency behavior. Hedging, which can issue concurrent attempts, is especially inappropriate when duplicate protection is missing.
| Result | Decision |
|---|---|
| 400 or 422 validation failure | Correct the payload; identical retries will not repair it |
| 401 or 403 | Fix credentials, scopes or account access |
| 409 idempotency conflict | Find why the same send ID was used with changed content |
| 429 | Respect Retry-After, preserve the job and reduce concurrency |
| 5xx | Retry within a bounded policy, retaining the same identifier |
| Timeout or connection reset | Treat acceptance as uncertain; reconcile or retry with the same identifier |
| Success but unreadable response | Preserve the operation identity; do not invent a fresh send |
For Sequenzy, the documented idempotency window is 14 days. A replay with the same key and request returns the original acceptance response; it does not prove the original email was delivered. Reusing the key with different content returns a conflict. Beyond the window, reconcile the existing notification before attempting another submission. A deliberate new message should have its own new notification ID.
Use capped backoff with jitter and an overall elapsed-time budget suitable for the message. A time-sensitive reset email and a monthly usage report need different expiry policies. Keep Retry-After handling and durable scheduling in the worker that owns that policy; do not claim the small adapter above implements a full retry engine.
Testing
Unit Test the Email Service
Use a fake HttpMessageHandler and assert the wire contract. Check the path, authorization header, idempotency key, recipient and body field. Return a realistic success object containing success and emailSendId; a test returning only an invented id field can make a broken response parser look correct.
Exercise at least a validation error, a permission failure, a rate limit, a transient server error, malformed success JSON and cancellation. Assert that one invocation makes one request, so adding a resilience handler later cannot silently change the duplicate-risk assumptions. For an exception after a possible acceptance, verify that your worker keeps the existing notification identifier.
Test templates with values such as <img src=x onerror=alert(1)>, apostrophes, non-Latin names and empty data. Assert that hostile text is encoded and no unexpected executable markup appears. A snapshot of a normal name will not catch an interpolation bug.
Integration Test with WebApplicationFactory
An ASP.NET Core integration test should replace the transport or its HTTP handler and exercise the actual domain endpoint. Assert permission checks and recipient selection, not just that a mocked sender was called. An authenticated user from another company must not be able to send that company's invoice or choose an arbitrary destination.
Keep provider calls mocked in automated tests. For a manual live smoke test, use an isolated sending account and an inbox you control, then inspect the resulting message. Compilation and mocked acceptance do not verify sender-domain configuration, mailbox placement or the provider's actual queue processing.
For the durable path, simulate a crash immediately after acceptance and then redeliver the job. Verify the second submission uses the same key and payload. Simulate a lease expiring while another worker claims the job. Those tests are more valuable than checking a private helper that simply returns a configured API base URL.
Going to Production
1. Verify Your Domain
Set up the sender identity and the provider's required DNS records. Check SPF, DKIM and your DMARC policy using the actual sending domain. A successful API call can still be suppressed or rejected downstream; inspect the recorded status before blaming template HTML.
Test at least one Gmail, one Outlook and one corporate recipient where practical. Those checks are observations, not a universal deliverability benchmark. Record the message type and sending domain so your team can compare a regression against an actual baseline.
2. Use a Dedicated Sending Domain
A sending subdomain can make ownership and DNS management clearer. Separating transactional and marketing streams also helps operational diagnosis. Neither choice automatically guarantees reputation isolation across every provider. Choose domains and streams deliberately, authenticate them, and monitor the actual outcomes.
3. Secure Your Secrets
Keep keys in server-side secret storage, grant only the access the application needs and document how to rotate them. Avoid logging authorization headers when enabling HTTP diagnostics. Treat message bodies as potentially sensitive: invoices contain financial information and recovery emails contain credentials that grant limited account access.
Review telemetry after adding a transport library or retry handler. Middleware that captures request bodies can expose secrets even if your own adapter logs only status codes. Mask credentials at the collection boundary and use retention appropriate to the data you actually need for troubleshooting.
Production Checklist
Before enabling customer traffic, decide who owns each layer: business event creation, durable storage, recipient authorization, rendering, submission, retries, downstream delivery events and support recovery. A provider solves some of those layers, not every application decision around them.
Confirm your worker is running in the deployed environment, not merely that jobs are being queued. Track oldest pending job age and failed attempts. A dashboard showing “job created” while no worker is available can look successful to an API caller and still send nothing.
Keep queue acceptance, provider acceptance and recipient-server delivery as separate metrics. Do not display a delivered status immediately after SendAsync returns. If the UI starts an asynchronous operation, make its current state observable and refresh it until it reaches a meaningful outcome.
Beyond Transactional: Marketing Emails and Sequences
Use consented marketing delivery for promotional or lifecycle messages where unsubscribe rules apply. Sequenzy's send API supports emailType: "marketing" with one recipient and managed unsubscribe handling. That is a different policy from the transactional adapter above, so model it explicitly rather than changing an unreviewed default globally.
For event-driven automations, send stable user identity, the business event name, its actual occurrence time and a caller-owned event identifier where the API supports it. Decide what historical imports should do; replaying a year of activity must not automatically welcome every existing customer again.
In B2B software, an event may belong to an account rather than an individual. A single person can belong to several organizations with different plans and roles. Include that relationship in the event contract so a trial-ending message for one workspace does not incorrectly describe the user's other paid workspace.
Frequently Asked Questions
Should I use SmtpClient or an email provider SDK in .NET?
For new SMTP work, consider MailKit; for an HTTP provider, either its maintained SDK or a typed client can work. Microsoft recommends alternatives to System.Net.Mail.SmtpClient for new development. Your infrastructure and operational needs should determine the transport.
Should I use the SendGrid SDK or HttpClient?
A maintained SDK reduces provider-specific DTO work. HttpClient makes the wire request explicit and can be enough for a small integration. SendGrid's Mail Send contract uses personalizations, from and content; it is not interchangeable with Sequenzy's subject and body request. Changing only the base URL is insufficient.
How do I register email services in ASP.NET Core's DI container?
Register the typed transport with AddHttpClient<IEmailSender, SequenzyEmailSender>() and inject IEmailSender into the application service that owns the notification. Keep settings on the server and validate required values before accepting traffic. Avoid capturing a transient typed client indefinitely inside a singleton.
How do I store email API keys securely in .NET?
Use User Secrets for local development and the deployment platform's secret mechanism in production. Keep the key out of checked-in JSON, client-side bundles and logs. Document how the application reloads or restarts after rotation so an emergency key change actually takes effect.
How do I send emails in the background in ASP.NET Core?
Use a durable job queue or a database outbox processed by a worker. A BackgroundService can host the processing loop, but its presence alone does not persist jobs. An in-memory channel is appropriate only when losing queued work is acceptable or the durable source can replay it.
How do I send to multiple recipients?
Check visibility semantics before using arrays. Sequenzy supports multiple to addresses for transactional messages, but recipients can see each other. For personalized customer notifications, submit one logical message per recipient. Its marketing delivery policy requires one recipient and does not support CC/BCC.
How do I prevent XSS in email templates?
Escape interpolated text and validate URLs before putting them into HTML attributes. Do not wrap arbitrary user HTML in Html.Raw. Test malicious values and inspect browser previews as well as actual emails; an email client stripping scripts does not make an unsafe web preview acceptable.
Can I use Razor views for email templates in .NET?
Yes, with an explicit renderer and the services it requires. Keep template models typed and test the renderer inside a background process if that is where it runs. Avoid assuming a controller's request context exists in a queue worker.
How do I handle email sending failures in ASP.NET Core?
Distinguish rejected requests from uncertain outcomes and downstream failures. Retry only with a stable notification identity and suitable provider support. Preserve permanent failures for inspection, and give support a deliberate recovery action instead of an unrestricted “resend everything” button.
How do I test email sending in .NET?
Mock the HTTP boundary for contract tests, then exercise the application workflow with its authorization and queue behavior. Run a separate manual smoke test with a controlled inbox. Neither a compile pass nor an HTTP 202 response proves inbox delivery.
How do I send templated emails with dynamic data in C#?
Render a typed, escaped template in your app or submit a saved provider template with documented variables. Preserve the payload or template version used by a retry. Avoid changing content while retaining the original idempotency key.
Can I send emails from a .NET minimal API?
Yes. The local route above demonstrates dependency injection and submission. A production route needs real authentication, authorization, rate limits and a trusted recipient-selection rule; do not publish the local test route as a generic send endpoint.
How do I handle rate limiting for email endpoints in ASP.NET Core?
Rate-limit the business action, such as requesting a reset, in addition to limiting HTTP traffic generally. Derive the account identity on the server, and avoid leaking whether an address exists through different public responses. Queue accepted work durably so a temporary provider limit does not discard it.
How do I respect the provider's rate limits when sending?
Control worker concurrency and schedule retries using the provider's documented budget and Retry-After response. Do not make every job sleep independently while holding scarce worker capacity. Preserve a visible pending state and alert when queue age grows beyond the message's useful lifetime.