TRENZ.Lib.RazorMail.MailKit
2.4.2
dotnet add package TRENZ.Lib.RazorMail.MailKit --version 2.4.2
NuGet\Install-Package TRENZ.Lib.RazorMail.MailKit -Version 2.4.2
<PackageReference Include="TRENZ.Lib.RazorMail.MailKit" Version="2.4.2" />
<PackageVersion Include="TRENZ.Lib.RazorMail.MailKit" Version="2.4.2" />
<PackageReference Include="TRENZ.Lib.RazorMail.MailKit" />
paket add TRENZ.Lib.RazorMail.MailKit --version 2.4.2
#r "nuget: TRENZ.Lib.RazorMail.MailKit, 2.4.2"
#:package TRENZ.Lib.RazorMail.MailKit@2.4.2
#addin nuget:?package=TRENZ.Lib.RazorMail.MailKit&version=2.4.2
#tool nuget:?package=TRENZ.Lib.RazorMail.MailKit&version=2.4.2
TRENZ.Lib.RazorMail
Templated transactional e-mail using Razor
This is a simple library you can use to write e-mail templates
in Razor syntax. That means you write raw HTML, but
elevated with C# — you get @foreach, @switch, and so on, and you get a strongly-typed model for custom data.
Installation
You currently need to create an ASP.NET app to use the razor mail renderer. See #7 for more information.
In NuGet, reference one of the available packages, depending on which MailSender backend you prefer. Currently, there
are three available:
System.Net.Mailcomes built into .NET and can be referenced viaTRENZ.Lib.RazorMail.SystemNet- MailKit is more modern and powerful than
System.Net.Mailand can be referenced viaTRENZ.Lib.RazorMail.MailKit - Using the Microsoft Graph API it is possible to send Mails via
the Microsoft 365 / Outlook.com service without using SMTP. It can be referenced via
TRENZ.Lib.RazorMail.MicrosoftGraph.
There is no need to reference TRENZ.Lib.RazorMail.Core directly.
Via dotnet:
Using System.Net.Mail
dotnet add package TRENZ.Lib.RazorMail.SystemNet
Using MailKit
dotnet add package TRENZ.Lib.RazorMail.MailKit
Using Microsoft Graph
dotnet add package TRENZ.Lib.RazorMail.MicrosoftGraph
Usage
In your Program.cs:
// use the default WebApplication builder (required for Razor engine)
var builder = WebApplication.CreateBuilder(args);
builder.AddControllers(); // NOT AddControllersWithViews()
builder.Services.AddRazorMailRenderer();
builder.Services.AddMailKitMailClient();
// or
builder.Services.AddSystemNetMailClient();
// or
builder.Services.AddMsGraphMailClient();
var app = builder.Build();
app.MapControllers();
// ...
A simple template looks like so:
@using TRENZ.Lib.RazorMail.SampleWebApi.Models
@inherits TRENZ.Lib.RazorMail.Core.MailTemplateBase<SampleModel>
@{
Subject = "Greetings!";
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<h1>@Model.Salutation!</h1>
</body>
</html>
Where SampleModel is:
public record SampleModel(string Salutation);
Notice that:
- we're passing
SampleModelas our model type. It has a propertySalutation, so we can then do@Model.Salutationto get its value. - we can set the
Subjectproperty, which becomes the e-mail subject.
Attachments
Inheriting from TRENZ.Lib.RazorMail.Core.MailTemplateBase<T> also gives us the convenience methods AttachFile() and
InlineFile(). These differ only in whether an attachment is intended for download, or for inline display.
For example, to show an image inline, you simply do:
<img src="@InlineFile("My Company Logo.png")" />
That's it. This attaches the image as a file, then references it using cid format[^1]. Because the image is attached,
this also doesn't require your users to enable loading external images, which some mail clients restrict for privacy
reasons.
[^1]: Each attachment becomes part of a MIME multipart message,
and is identified by its Content-ID. To refer to that part, RazorMail then uses the cid:(Content-ID) URI scheme.
Or, to attach a file:
@{
AttachFile("Invoice.pdf", someByteArray);
}
(Because file attachments don't relate to the body, you probably want to put this near the Subject.)
Sending
Depending on which NuGet package you've picked above, you get a backend for sending either via the classic
System.Net.Mail, or via MailKit/MimeKit.
You can also pass a callback to the mail clients to configure default headers (setting a global From header, for
example).
The IMailRenderer is a scoped service.
This means you will either need to register your service as a scoped service or obtain a scope using this code:
await using var scope = serviceProvider.CreateScopeAsync();
var renderer = scope.ServiceProvider.GetRequiredService<IMailRenderer>();
This is how you would actually render and send an e-mail:
const string viewName = "Sample";
// this is your model. If you're sending to multiple people, you may want to customize this per person.
var model = new SampleModel(request.Salutation);
// this renders your view (your e-mail template), with the above model as an argument).
IMailRenderer renderer = ...; // inject via DI, for example
var content = await renderer.RenderAsync(viewName, model);
// this wraps the rendered HTML and passes it to a service that handles sending.
// You need someone to send from, and one or more recipients.
var mail = new MailMessage
{
Headers = new()
{
Recipients = [request.To],
// here you can add CC, BCC and other headers
},
Content = content,
};
// this actually sends the e-mail
IMailClient client = ...; // inject via DI or use MailKitMailClient or SystemNetMailClient directly
await client.SendAsync(mail);
Microsoft Graph Considerations
The Microsoft Graph API (MsGraph) is a powerful API provided by Microsoft. There are currently two modes in which this
library can be used with MsGraph. It is able to send mails either on behalf of user (delegated) or as every user in a
tenant (application). Configuration of the MsGraph portion of this library is done via the appsettings.json file.
Example .json section:
{
"MsGraphOptions": {
"TenantId": "your_tenant_id",
"ClientId": "your_client_id",
"ClientSecret": "your_secret",
"SaveToSentItems": false,
"RedirectUri": "your_redirect_id",
"Delegated": true,
"UseUploadSessions": true
}
}
In order for the MsGraph portion of this library to be able to work properly, it needs to have permissions set according to
your chosen mode. MsGraph uses
the Microsoft identity platform to handle
authentication. To be able to use this platform and by extension use it in your project that references TRENZ.Lib.RazorMail.MicrosoftGraph, it must be registered as an app
via the Microsoft Entra Admin center. A reference and starting point can be
found here.
TenantId and ClientId can be found in that app registration, the ClientSecret can be created there as well. Note
that SaveToSentItems which is intended to grant the option of saving a sent mail to the inbox only works if a mail is
sent without attachments. The option UseUploadSessions refers to how attachments shall be handled.
Microsoft's documentation implies that for any attachments that are larger than 3 MB an upload session should be created.
This invlolves saving the mail to the mailbox, attaching the files to it via this upload session and finally sending the mail.
At the point of writing it is possible to simply use the workflow without upload session for every attachment.
This allows handling attachments of larger sizes without needing the Mail.ReadWrite permission.
With Application Permissions
If it is wished to run this library with application level permissions, the field RedirectUri is not needed and
Delegated should be set to false. The needed Permission in that case are Mail.ReadWrite and Mail.Send (type
Application). Note that with application level permissions mails can be sent as any user in the tenant. The Permission
Mail.ReadWrite is additionally needed because of the way attachments are done in Outlook, see the Microsoft
documentation here for more details.
With Delegated Permission
Using this library on behalf of a user necessitates authentication of that user. The authentication is done on the basis
of
the OAuth 2.0 authorization code grant flow
as described by Microsoft. The persmissions needed are Mail.ReadWrite, Mail.Send, User.Read and offline_access
(type Delegated). In order for the authentication process to work a browser needs to be installed. Furthermore a
redirect uri must be defined and set in the appsettings.json as well as in the app registration. This redirect uri
should point towards your application where the authorization code can be handed to the
InitializeGraphClientViaAuthCode() function defined in MsGraphDelegatedMailClient. This is the IMailClient which
is registered via AddMsGraphMailClient() when Delegated is true in the appsettings.json.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. 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. |
-
net8.0
- JetBrains.Annotations (>= 2026.2.0)
- MailKit (>= 4.15.1)
- TRENZ.Lib.RazorMail.Core (>= 2.4.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
# 2.4.1
- Fixes publish TRENZ.Lib.RazorMail.MicrosoftGraph to NuGet
# 2.4.0
- Added support for the Microsoft Graph API
# 2.3.1
- Security: Updated `MailKit` to 4.15.1
# 2.3.0
- Added support for setting a message importance (`Importance`, `X-Priority`) [#26](https://github.com/trenz-gmbh/TRENZ.Lib.RazorMail/pull/26) by @chucker
- Fixed a NRE when sending mails without attachments [#29](https://github.com/trenz-gmbh/TRENZ.Lib.RazorMail/pull/30) by @ricardoboss
# 2.2.0
- Added some badges to the README
- Marked `AddRazorEmailRenderer` obsolete, use `AddRazorMailRenderer` instead
- Marked `AddMailKitRazorMailClient` obsolete, use `AddMailKitMailClient` instead
- Marked `AddSystemNetRazorMailClient` obsolete, use `AddSystemNetMailClient` instead
- Added `configureClient` parameter to `AddMailKitMailClient` and `AddSystemNetMailClient` so you can configure the
client instance (e.g. default headers)
# 2.1.1
- Initial nuget.org release
- No feature changes, just a version bump