The Problem
Your application needs to send welcome emails, password resets, and order confirmations. You're concatenating HTML strings in C# code, hardcoding SMTP credentials, and praying the email actually arrives. When it fails, there's no retry logic — the user just never gets their confirmation.
You need a proper email system: Razor templates for HTML content, provider abstraction so you can swap SMTP for SendGrid without rewriting code, and automatic retries when the mail server hiccups.
Ingredients
Noundry.Sanquhar
vlatest
Core email library with SMTP support and Razor templating
Noundry.Sanquhar.SendGrid
vlatest
Optional SendGrid provider for high-volume sending
.NET 10 SDK
v10.0
Target framework for the project
Start with the core package. Add a provider package only if you need SendGrid or Mailgun — SMTP is built in.
Preparation
dotnet add package Noundry.Sanquhar
# Optional: Add SendGrid support
dotnet add package Noundry.Sanquhar.SendGrid
2. Configure in appsettings.json
{
"Sanquhar": {
"TemplatePath": "EmailTemplates",
"EnableTemplateCache": true,
"Resilience": {
"Enabled": true,
"MaxRetryAttempts": 3,
"CircuitBreakerThreshold": 5,
"TimeoutSeconds": 30
},
"Smtp": {
"Host": "smtp.example.com",
"Port": 587,
"Username": "[email protected]",
"Password": "your-smtp-password",
"EnableSsl": true
},
"Mail": {
"DefaultFrom": "[email protected]",
"DefaultFromName": "My Application",
"EnableEmailValidation": true
}
}
}
3. Create the EmailTemplates directory
mkdir EmailTemplates
The Code
Sanquhar uses a three-file convention for templates: {Name}.cshtml for HTML, {Name}_Subject.cshtml for the subject line, and an optional {Name}_Text.cshtml for plain text fallback.
Let's build a complete order confirmation email system.
using Noundry.Sanquhar.Extensions;
var builder = WebApplication.CreateBuilder(args);
// One line to register everything: templates, SMTP, validation, caching
builder.Services.AddSanquhar(builder.Configuration);
// To use SendGrid instead of SMTP:
// using Noundry.Sanquhar.SendGrid.Extensions;
// builder.Services.AddSanquhar(builder.Configuration, options =>
// options.UseSendGrid(builder.Configuration));
builder.Services.AddScoped<OrderEmailService>();
var app = builder.Build();
app.Run();
namespace MyApp.Models;
public class OrderConfirmationModel
{
public string CustomerName { get; set; } = string.Empty;
public string OrderNumber { get; set; } = string.Empty;
public DateTime OrderDate { get; set; }
public decimal Total { get; set; }
public List<LineItem> Items { get; set; } = [];
public string TrackingUrl { get; set; } = string.Empty;
}
public class LineItem
{
public string ProductName { get; set; } = string.Empty;
public int Quantity { get; set; }
public decimal Price { get; set; }
}
@model MyApp.Models.OrderConfirmationModel
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: -apple-system, sans-serif; background: #f5f5f5; margin: 0; padding: 20px; }
.container { max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; }
.header { background: linear-gradient(135deg, #f59e0b, #ea580c); color: white; padding: 30px; text-align: center; }
.content { padding: 30px; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
th { background: #f5f5f5; padding: 10px; text-align: left; }
td { padding: 10px; border-bottom: 1px solid #eee; }
.total { font-size: 24px; font-weight: bold; color: #f59e0b; }
.btn { display: inline-block; background: #f59e0b; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Order Confirmed!</h1>
</div>
<div class="content">
<p>Hi @Model.CustomerName,</p>
<p>Thanks for your order! Here's your receipt:</p>
<p><strong>Order #@Model.OrderNumber</strong> — @Model.OrderDate.ToString("MMMM d, yyyy")</p>
<table>
<tr><th>Item</th><th>Qty</th><th>Price</th></tr>
@foreach (var item in Model.Items)
{
<tr>
<td>@item.ProductName</td>
<td>@item.Quantity</td>
<td>@item.Price.ToString("C")</td>
</tr>
}
</table>
<p class="total">Total: @Model.Total.ToString("C")</p>
<p><a href="@Model.TrackingUrl" class="btn">Track Your Order</a></p>
</div>
</div>
</body>
</html>
@model MyApp.Models.OrderConfirmationModel
Order Confirmed: #@Model.OrderNumber
using Noundry.Sanquhar.Models;
using Noundry.Sanquhar.Services;
using Noundry.Sanquhar.Validation;
using MyApp.Models;
namespace MyApp.Services;
public class OrderEmailService
{
private readonly IMailService _mail;
private readonly IEmailValidator _validator;
private readonly ILogger<OrderEmailService> _logger;
public OrderEmailService(
IMailService mail,
IEmailValidator validator,
ILogger<OrderEmailService> logger)
{
_mail = mail;
_validator = validator;
_logger = logger;
}
public async Task<bool> SendOrderConfirmationAsync(
string customerEmail, OrderConfirmationModel model)
{
if (!_validator.IsValid(customerEmail))
{
_logger.LogWarning("Invalid email: {Email}", customerEmail);
return false;
}
try
{
// Option A: One-liner — create from template and send
await _mail.SendFromTemplateAsync(
"OrderConfirmation", model, customerEmail);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send order confirmation to {Email}",
customerEmail);
return false;
}
}
public async Task SendWithAttachmentAsync(
string customerEmail, OrderConfirmationModel model, byte[] invoicePdf)
{
// Option B: Two-step — create, customize, then send
var message = await _mail.CreateFromTemplateAsync(
"OrderConfirmation", model);
message.To.Add(customerEmail);
message.Bcc.Add("[email protected]");
message.Priority = MailPriority.High;
message.Attachments.Add(new MailAttachment
{
FileName = $"Invoice-{model.OrderNumber}.pdf",
Content = invoicePdf,
ContentType = "application/pdf"
});
await _mail.SendAsync(message);
}
}
Plating
You now have a production-grade email system:
- Razor templates with full C# expression support — no more string concatenation
- Provider abstraction — switch from SMTP to SendGrid by changing one line in
Program.cs - Automatic retries with exponential backoff and circuit breaker protection
- Template caching so Razor compilation happens once, not on every send
- Email validation via RFC 5322-compliant
IEmailValidator - OpenTelemetry metrics track emails sent, failures, and latency
Provider swap is one line:
// SMTP (default)
builder.Services.AddSanquhar(builder.Configuration);
// SendGrid
builder.Services.AddSanquhar(builder.Configuration, o => o.UseSendGrid(builder.Configuration));
// Mailgun
builder.Services.AddSanquhar(builder.Configuration, o => o.UseMailgun(builder.Configuration));
Next steps:
- Create a
PasswordResettemplate with time-limited tokens - Add a background email queue with
IServiceScopeFactoryfor non-blocking sends - Use the
_Text.cshtmlsuffix for plain text fallbacks that improve deliverability
Was this recipe helpful?
Chef George
.NET Architect & Head Chef
25+ years crafting enterprise C# solutions. Creator of the Noundry platform. Passionate about clean architecture, cloud-agnostic deployments, and code that cooks.