The shortest possible send.
await mailer.Send(
sender: new MailAddress { Email = "no-reply@example.com" },
recipients: [new MailRecipient { Email = "alice@example.com" }],
subject: "Order confirmed",
message: "<p>Your order <strong>#1042</strong> has been received.</p>"
);
Build a MessageObject when you need fine-grained control over recipients, reply-to, or plain text.
var message = new MessageObject
{
From = new MailAddress { Email = "orders@example.com", DisplayName = "Example Shop" },
ReplyTo = new MailAddress { Email = "support@example.com" },
To =
[
new MailRecipient { Email = "alice@example.com", DisplayName = "Alice" },
new MailRecipient { Email = "bob@example.com", RecipientType = RecipientTypes.Cc },
new MailRecipient { Email = "archive@example.com", RecipientType = RecipientTypes.Bcc },
],
Subject = "Invoice #1042",
Body = "<h1>Invoice</h1><p>See the attached PDF.</p>",
IsHtml = true
};
try
{
await mailer.Send(message); // a returned response is a success
}
catch (MailException ex) // Regira.Office.Mail.Exceptions: the provider refused it
{
logger.LogError(ex, "Mail failed: {Content}", ex.ResponseContent);
}
Attach one or more files by passing BinaryFileItem instances in the Attachments collection.
public async Task SendInvoice(IMailService mailer, string recipientEmail, byte[] pdfBytes)
{
var message = new MessageObject
{
From = "billing@example.com",
To = [new MailRecipient { Email = recipientEmail }],
Subject = "Your invoice",
Body = "<p>Please find your invoice attached.</p>",
Attachments =
[
new BinaryFileItem { FileName = "invoice.pdf", Bytes = pdfBytes, ContentType = "application/pdf" }
]
};
await mailer.Send(message);
}
Drive the backend choice from configuration — consuming code only sees IMailService.
using Regira.Office.Mail.SendGrid.DependencyInjection; // AddSendGrid
using Regira.Office.Mail.MailGun.DependencyInjection; // AddMailGun
using Regira.Office.Mail.MailKit.DependencyInjection; // AddMailKit
using MailKit.Security; // SecureSocketOptions
var backend = configuration["Mail:Backend"];
if (backend == "mailgun")
{
services.AddMailGun(cfg =>
{
cfg.Api = configuration["Mail:MailGun:Api"]!;
cfg.Key = configuration["Mail:MailGun:Key"]!;
cfg.Domain = configuration["Mail:MailGun:Domain"]!;
});
}
else if (backend == "smtp")
{
services.AddMailKit(cfg =>
{
cfg.Host = configuration["Mail:Smtp:Host"]!;
cfg.Port = int.Parse(configuration["Mail:Smtp:Port"] ?? "587");
cfg.Security = Enum.Parse<SecureSocketOptions>(configuration["Mail:Smtp:Security"] ?? "StartTls");
cfg.UserName = configuration["Mail:Smtp:UserName"];
cfg.Password = configuration["Mail:Smtp:Password"];
});
}
else
{
services.AddSendGrid(cfg =>
cfg.Key = configuration["Mail:SendGrid:Key"]!);
}
Use MailInput from Mail.Web to receive and validate a send request over HTTP. The caller chooses the recipients, the body and the attachments, so the endpoint requires a signed-in user and sends from the app’s own address; limit the recipients to the ones the app allows as well.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Regira.Office.Mail.Abstractions; // IMailService
using Regira.Office.Mail.Exceptions; // MailException
using Regira.Office.Mail.Models; // MailAddress
using Regira.Office.Mail.Web;
[ApiController]
[Authorize]
[Route("mail")]
public class MailController(IMailService mailer, ILogger<MailController> logger) : ControllerBase
{
[HttpPost("send")]
public async Task<IActionResult> Send([FromBody] MailInput input)
{
var message = input.ToMessageObject();
message.From = new MailAddress { Email = "no-reply@example.com" }; // the app's sender, not the caller's
try
{
var result = await mailer.Send(message);
return Ok(new { result.Status });
}
catch (MailException ex) // the provider refused the message: log its reply, don't return it
{
logger.LogWarning(ex, "Mail refused: {Response}", ex.ResponseContent);
return StatusCode(502);
}
}
}
A JSON body accepted by this endpoint:
{
"to": [{ "email": "alice@example.com" }],
"subject": "Hello",
"body": "<p>Hi Alice!</p>",
"isHtml": true
}
Plug IMailService into the Identity email confirmation flow using IdentityMailer.
using Microsoft.AspNetCore.Identity.UI.Services; // IEmailSender
using Regira.Office.Mail.SendGrid.DependencyInjection; // AddSendGrid
using Regira.Office.Mail.Abstractions; // IMailService
using Regira.Office.Mail.Models; // MailAddress
using Regira.Security.Authentication.Web.Mail; // IdentityMailer, IdentityMailerOptions
services.AddSendGrid(cfg => cfg.Key = configuration["Mail:SendGrid:Key"]!);
services.AddSingleton<IEmailSender>(provider =>
new IdentityMailer(
provider.GetRequiredService<IMailService>(),
new IdentityMailerOptions
{
Sender = new MailAddress
{
Email = "no-reply@example.com",
DisplayName = "Example App"
},
FormatPlainText = true // the Regira account mails are plain text: encode it, link the URL, keep the line breaks
}
));
IEmailSender.SendEmailAsync is now backed by your chosen IMailService implementation. All Identity-generated emails (confirmation, password reset, etc.) flow through SendGrid or Mailgun automatically.