affolterNET.Graph.Smtp 1.3.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package affolterNET.Graph.Smtp --version 1.3.1
                    
NuGet\Install-Package affolterNET.Graph.Smtp -Version 1.3.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="affolterNET.Graph.Smtp" Version="1.3.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="affolterNET.Graph.Smtp" Version="1.3.1" />
                    
Directory.Packages.props
<PackageReference Include="affolterNET.Graph.Smtp" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add affolterNET.Graph.Smtp --version 1.3.1
                    
#r "nuget: affolterNET.Graph.Smtp, 1.3.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package affolterNET.Graph.Smtp@1.3.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=affolterNET.Graph.Smtp&version=1.3.1
                    
Install as a Cake Addin
#tool nuget:?package=affolterNET.Graph.Smtp&version=1.3.1
                    
Install as a Cake Tool

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 inject IEmailSender
  • Options pattern: configure via IConfiguration binding or Action<>
  • 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 as 1.0.0-preview.{run_number}
  • Tag v*: publishes with the tag version (e.g. v1.1.0 → 1.1.0)

License

MIT

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.3 873 8/18/2026
1.3.2 137 8/17/2026
1.3.1 158 8/2/2026
1.2.8 137 8/2/2026
1.2.7 457 4/30/2026
1.2.6 128 4/30/2026
1.2.5 198 3/28/2026
1.2.4 298 2/12/2026
1.2.3 164 2/11/2026