affolterNET.Graph.Smtp
1.3.3
dotnet add package affolterNET.Graph.Smtp --version 1.3.3
NuGet\Install-Package affolterNET.Graph.Smtp -Version 1.3.3
<PackageReference Include="affolterNET.Graph.Smtp" Version="1.3.3" />
<PackageVersion Include="affolterNET.Graph.Smtp" Version="1.3.3" />
<PackageReference Include="affolterNET.Graph.Smtp" />
paket add affolterNET.Graph.Smtp --version 1.3.3
#r "nuget: affolterNET.Graph.Smtp, 1.3.3"
#:package affolterNET.Graph.Smtp@1.3.3
#addin nuget:?package=affolterNET.Graph.Smtp&version=1.3.3
#tool nuget:?package=affolterNET.Graph.Smtp&version=1.3.3
affolterNET.Graph.Smtp
A .NET 9.0 library for sending emails via Microsoft Graph API or SMTP with OAuth2 (XOAUTH2), using client credentials flow (application permissions). Includes a configurable branded HTML email template.
Features
- Two backends: Microsoft Graph API and SMTP (via MailKit + XOAUTH2)
- OAuth2 client credentials flow using MSAL (no user interaction required)
- Branded HTML template: configurable colors, logo, company name, footer
- DI-friendly: register with
AddEmailSender()and injectIEmailSender - Options pattern: configure via
IConfigurationbinding orAction<> - Supports HTML body, multiple recipients (To/Cc/Bcc), and file attachments
Installation
GitHub Packages
Add the GitHub NuGet source:
dotnet nuget add source "https://nuget.pkg.github.com/affolterNET/index.json" \
--name "affolterNET" \
--username YOUR_GITHUB_USERNAME \
--password YOUR_GITHUB_PAT
Install the package:
dotnet add package affolterNET.Graph.Smtp
Prerequisites
Azure App Registration
Create an app registration with application permissions (requires admin consent):
| Backend | Permission | Scope |
|---|---|---|
| Graph API | Mail.Send |
https://graph.microsoft.com/.default |
| SMTP | SMTP.SendAsApp |
https://outlook.office365.com/.default |
For SMTP, the sending mailbox also needs SMTP AUTH enabled:
Set-CASMailbox -Identity "noreply@yourdomain.com" -SmtpClientAuthenticationDisabled $false
Restricting the app to one mailbox
Both permissions above are tenant-wide. An application permission is not tied to the
mailbox you configure as SenderEmail — Mail.Send and SMTP.SendAsApp authorize sending
as any mailbox in the organization, and Set-CASMailbox above only enables SMTP AUTH on
the sending mailbox, it does not restrict the app. Scope the grant explicitly.
Use RBAC for Applications in Exchange Online. (Application Access Policies —
New-ApplicationAccessPolicy — do the same job but are
legacy
and must not be used for new configuration.) After Connect-ExchangeOnline, as a member of
the Organization Management role group:
# 1. Point Exchange at the existing Entra service principal.
# Take both IDs from Entra > Enterprise applications, NOT from App registrations.
New-ServicePrincipal -AppId <client id> -ObjectId <service principal object id> `
-DisplayName "my-mail-app"
# 2. Describe the mailboxes the app may act on.
New-ManagementScope -Name "my-mail-sender" `
-RecipientRestrictionFilter "Alias -eq 'noreply'"
# 3. Grant the role within that scope. Use "Application SMTP.SendAsApp" for the SMTP backend.
New-ManagementRoleAssignment -App <service principal object id> `
-Role "Application Mail.Send" -CustomResourceScope "my-mail-sender"
# 4. Verify: InScope must be True for the sender and False for anything else.
Test-ServicePrincipalAuthorization -Identity <service principal object id> `
-Resource noreply@yourdomain.com | Format-Table
Then remove the tenant-wide consent in Entra. Entra grants and Exchange grants are a
union, not an intersection: an unscoped Mail.Send left in Entra keeps working on its own
and the scope above has no effect. Microsoft's rule of thumb is that organization-wide
permissions belong in Entra and resource-scoped ones in Exchange RBAC — for a single sending
mailbox, only the latter should remain. Permission changes are cached for 30 minutes to
2 hours; Test-ServicePrincipalAuthorization bypasses that cache.
Details: RBAC for Applications in Exchange Online.
Usage
Configuration
Add to appsettings.json:
{
"Email": {
"TenantId": "your-tenant-id",
"ClientId": "your-client-id",
"ClientSecret": "your-client-secret",
"SenderEmail": "noreply@yourdomain.com",
"Provider": "Graph",
"Template": {
"AccentColor": "#f49900",
"LogoUrl": "https://example.com/logo.png",
"CompanyName": "My Company",
"WebsiteUrl": "https://example.com"
}
}
}
Provider can be "Graph" (default) or "Smtp".
DI Registration
using affolterNET.Graph.Smtp.DependencyInjection;
// Option 1: Bind from IConfiguration section (recommended)
builder.Services.AddEmailSender(builder.Configuration.GetSection("Email"));
// Option 2: Manual configuration
builder.Services.AddEmailSender(
options =>
{
options.TenantId = "...";
options.ClientId = "...";
options.ClientSecret = "...";
options.SenderEmail = "noreply@yourdomain.com";
options.Provider = EmailSenderProvider.Graph;
},
template =>
{
template.AccentColor = "#40AEAB";
template.CompanyName = "My Company";
});
Sending Email
using affolterNET.Graph.Smtp;
public class MyService(IEmailSender emailSender)
{
public async Task SendWelcomeEmail(string recipient)
{
await emailSender.SendAsync(new EmailMessage
{
To = recipient,
Subject = "Welcome",
HtmlBody = "<h1>Welcome!</h1><p>Thanks for signing up.</p>"
});
}
}
Email Template
Use EmailTemplate.Render() to wrap content in a branded HTML layout:
// Default branding (affolterNET)
var html = EmailTemplate.Render("<h2>Hello</h2><p>Your content here.</p>");
// Custom branding
var html = EmailTemplate.Render(
new EmailTemplateOptions
{
AccentColor = "#40AEAB",
AccentHoverColor = "#369996",
LogoUrl = "https://example.com/logo.png",
CompanyName = "My Company",
WebsiteUrl = "https://example.com"
},
"<h2>Hello</h2><p>Your content here.</p>");
await emailSender.SendAsync(new EmailMessage
{
To = "user@example.com",
Subject = "Welcome",
HtmlBody = html
});
The template matches the Keycloak email theme style (white card, accent-colored header border and buttons, footer with company info).
Template Options
| Property | Default | Description |
|---|---|---|
AccentColor |
#f49900 |
Primary color (header border, buttons, links) |
AccentHoverColor |
#d98600 |
Button hover color |
TextColor |
#333333 |
Main text color |
SecondaryTextColor |
#555555 |
Paragraph text color |
MutedTextColor |
#888888 |
Footer/notice text color |
BackgroundColor |
#f5f7fa |
Page background |
CardBackgroundColor |
#ffffff |
Email card background |
FooterBackgroundColor |
#fafafa |
Footer background |
BorderColor |
#eeeeee |
Footer border color |
FontFamily |
Source Sans Pro, Arial, ... | Font stack |
LogoUrl |
https://affolter.net/media/website/logo.png |
Logo image URL (set null for text) |
LogoAlt |
affolterNET |
Logo alt text |
LogoHeight |
40 |
Logo height in pixels |
CompanyName |
affolterNET |
Company name (header fallback + footer) |
WebsiteUrl |
https://affolter.net |
Footer link |
FooterHtml |
null |
Custom footer HTML (overrides default) |
Use CSS classes button, link-text, and notice in your body HTML for consistent styling.
Sending Through an Egress Proxy (no client credential)
The Graph backend can route through a proxy that authenticates the call itself, so the application holds no client secret at all. Two options control this:
services.AddEmailSender(options =>
{
options.SenderEmail = "noreply@example.com";
options.GraphBaseUrl = "http://egress-proxy:8080/graph-mail";
options.ProxyProvidesAuthorization = true;
// TenantId / ClientId / ClientSecret stay unused in this mode.
});
GraphBaseUrl replaces only the host part — the request path stays
/v1.0/users/{SenderEmail}/sendMail, so the proxy sees a stable URL it can allowlist. With
ProxyProvidesAuthorization the sender skips MSAL entirely and sends no Authorization
header; the proxy is expected to attach one, for example from a federated workload identity.
Both default to the public Graph endpoint and the MSAL client-credentials flow, so existing configurations are unaffected. This mode applies to the Graph backend only — the SMTP backend speaks XOAUTH2 directly and always needs its own credential.
Multiple Recipients
Separate addresses with semicolons:
new EmailMessage
{
To = "user1@example.com;user2@example.com",
Cc = "manager@example.com",
Subject = "Team Update",
HtmlBody = "<p>Update for the team.</p>"
}
Attachments
new EmailMessage
{
To = "user@example.com",
Subject = "Report",
HtmlBody = "<p>Please see the attached report.</p>",
Attachments =
[
new EmailAttachment
{
FileName = "report.pdf",
Content = File.ReadAllBytes("report.pdf"),
ContentType = "application/pdf"
}
]
}
Development
dotnet build
dotnet test
Integration Tests
Integration tests require real Azure credentials via environment variables:
EMAIL_TENANT_ID="..." \
EMAIL_CLIENT_ID="..." \
EMAIL_CLIENT_SECRET="..." \
EMAIL_SENDER="noreply@yourdomain.com" \
dotnet test --filter "IntegrationTest"
CI/CD
The GitHub Actions workflow (.github/workflows/build-publish.yml) builds, tests, and publishes to GitHub Packages:
- Push to
main: publishes as1.0.0-preview.{run_number} - Tag
v*: publishes with the tag version (e.g.v1.1.0→1.1.0)
License
MIT
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net9.0
- MailKit (>= 4.16.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.15)
- Microsoft.Extensions.Http (>= 9.0.15)
- Microsoft.Extensions.Options (>= 9.0.15)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 9.0.15)
- Microsoft.Identity.Client (>= 4.83.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.