

Update 2020-06-20: Update for new Razor Class Library options for “support pages and views” option that is required for this to work.

Update 2020-04-18: As of .NET Core 3, ASP.NET Core targets .NET Core directly, instead of .NET Standard.  This means you cannot use a .NET Standard Class Library and reference ASP.NET Core.  Please see this repo for an example of getting Razor Emails working with .NET Core 3.1.  This post has been updated to just reference a .NET Core Library instead of .NET Standard Library.



Full Code: https://github.com/scottsauber/RazorHtmlEmails











Also, I want to be able to generate these HTML Emails from within a .NET Class Library, so that the sending of the emails happens right next to all my other business logic.


So at a high level, the requirements are:

  3. Use Razor.
  4. Be able to call it from a .NET Core Class Library.






Enter Razor Class Libraries







Alright then, let the walkthrough begin!


Create an ASP.NET Core Web Application


With Visual Studio:

  1. File
  2. New Project
  3. ASP.NET Core Web Application
    1. I just called it RazorHtmlEmails.AspNetCore
  4. Web Application
  5. OK


Or with the command line:

  1. dotnet new sln -n RazorHtmlEmails
  2. dotnet new razor -n RazorHtmlEmails.AspNetCore
  3. dotnet sln RazorHtmlEmails.sln add RazorHtmlEmails.AspNetCore

GitHub commit here


Create a Razor Class Library

Next – create an ASP.NET Core Razor Class Library.

With Visual Studio:

  1. Right-click the Solution
  2. Add
  3. New Project
  4. Razor Class Library
  5. Next
  6. Give it a name, I just called it RazorHtmlEmails.RazorClassLib
  7. Create
  8. Check the box for “Support pages and views” in the bottom right
    1. 2020-06-20_15-01-08
  9. Create


Or… with the command line (NOTE: the -s for “support pages and views”):

  1. dotnet new razorclasslib -n RazorHtmlEmails.RazorClassLib -s
  2. dotnet sln RazorHtmlEmails.sln add RazorHtmlEmails.RazorClassLib



GitHub commit here


Create the RazorViewToStringRenderer class




GitHub commit here


Create your base HTML Email Layout



The layout looks like this:







  2. Add an EmailLayout.cshtml to that folder
  3. Add the following code and try not to pass out












GitHub commit here


Create a HTML Email Button Partial for re-usability



A good example of this is the button:





  1. Under /Views/Shared add a EmailButtonViewModel.cs class
  2. Add the following code:


3. Add an EmailButton.cshtml file
4. Add the following code:





GitHub commit here

Create your HTML Email Content





4. Add a ConfirmAccountEmailViewModel.cs file with the following code:

5. Add a ConfirmAccount.cshtml file with the following code:



GitHub commit here


Create a .NET Core Class Library



So let’s create a .NET Core Class Library.  If you want you can create a .NET Core Library and it’ll work as well.

With Visual Studio:

  1. Right-click the Solution
  2. Add
  3. New Project
  4. Class Library (.NET Core)
    1. I just called it RazorHtmlEmails.Common
  5. OK


Or with the command line:

  1. dotnet new classlib -n RazorHtmlEmails.Common -f netcoreapp3.1
  2. dotnet sln RazorHtmlEmails.sln add RazorHtmlEmails.Common


Then delete out Class1.cs

GitHub commit here


Call the RazorViewToStringRenderer in your business logic






GitHub commit here


Hook it up to the UI





GitHub commit here









Hope this helps!

84 thoughts on “Walkthrough: Creating an HTML Email Template with Razor and Razor Class Libraries

  1. it doesnt work when i am trying to call it from Web API. the problem cannot find view in GetView or FindView method always back with null


  2. Hi Scott,
    Great solution, however I hit one issue,
    If I call _razorViewToStringRenderer.RenderViewToStringAsync a few times in a row will be fine.
    But if I call
    _razorViewToStringRenderer.RenderViewToStringAsync and in the middle I call others services, when I call
    _razorViewToStringRenderer.RenderViewToStringAsync again the httpContext.RequestServices always zero, exception caught is the serviceprovider is disposed.
    Have you found similar issues to this?

    Many thanks

    private ActionContext GetActionContext()
    var httpContext = new DefaultHttpContext();
    httpContext.RequestServices = _serviceProvider;
    return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());


    • Hey Jim,

      I have not hit this issue. What I would look for is to see if one of your services is using the IServiceProvider directly and manipulating it in some way. It being disposed is a little odd. Any chance you could share code of what’s going on so I could take a deeper look?


      • Hi Scott, many thanks for your quick reply, no the other service does not use IServiceProvider directly. And one thing if the service use UserManager and the the ServiceProvider injected into the RazorViewToStringRendered constructor will be null. I will get the source code soon to share. Thanks again.

        Liked by 1 person

      • This will work:
        var infoEmail = _configuration.GetSection(“Email:InfoEmail”).Value;
        var body = await _emailTemplateService.RenderViewToStringAsync(“/Views/Template/ConfirmAccountEmail.cshtml”, model);
        var body2 = await _emailTemplateService.RenderViewToStringAsync(“/Views/Template/ConfirmAccountEmail.cshtml”, model);

        await _postmarkEmailService.SendAsync(notification.Email, “Confirm your registration”, body);
        await _postmarkEmailService.SendAsync(infoEmail, “New member registration”, body2);

        This will NOT work:
        var infoEmail = _configuration.GetSection(“Email:InfoEmail”).Value;


        this is the postmarkService only use Iconfiguration, and not only postmarkService, most of the services, the problem is with hpptcontext.RequestServices which assigned by serviceprovider.

        public class PostmarkEmailService : IPostmarkEmailService
        protected readonly IConfiguration _config;
        private readonly PostmarkClient _client;
        private readonly ILogger _logger;
        private readonly bool _emailEnabled;
        private readonly string _from;
        private readonly string _bcc;
        private readonly string _emailOverride;

        public PostmarkEmailService(IConfiguration config
        //ILoggerFactory loggerFactory
        //_logger = loggerFactory.CreateLogger();
        _config = config;
        _client = new PostmarkClient(_config.GetSection(“Email:PostmarkApiKey”).Value);
        _emailEnabled = _config.GetSection(“Email:Enabled”).Value.ToLower() == “true”;
        _from = _config.GetSection(“Email:From”).Value;
        _bcc = null == _config.GetSection(“Email:Bcc”) ? string.Empty : _config.GetSection(“Email:Bcc”).Value;
        _emailOverride = null == _config.GetSection(“Email:Override”) ? string.Empty : _config.GetSection(“Email:Override”).Value;


        Many thanks


  3. So this essentially still requires an ASP project? How do you test it? How do you get the dependencies it needs in a test project?


  4. Scott, you rock. I just implemented this in an Asp.Net Core Web API that sends email notifications, and it’s so much better than what I was doing before.

    Liked by 1 person

  5. Just want to say this walk-through was extremely helpful in implementing email sending in my app!

    One tip I would like to pass on: Do your styles properly with styles defined in the header like it was a standard web-page – then run it through an inliner such as PreMailer (free – on Nuget) and it will magically move all those styles in line.

    I updated RazorViewToStringRenderer to include such a call and it works great!


  6. This is absolutely awesome, I got this up and running in no time. I included PreMailer.Net to inline my css styles in my RazorViewToStringRenderer so I can design my templates using classes, it worked very well for me!

    Liked by 1 person

  7. Hi great write up and works striaght out of the box as it is.
    However I’ve been trying to implement this into a WebAPI application. Application structure is MVC talking to a WebAPI backend. However when I call the _viewEngine.GetView this never finds my view? any help would be great


      • Hey Matheus, do you happen to have a repro of the problem that I could take a look? Is it because in ConfigureServices there’s only `services.AddControllers` and not `services.AddControllersWithViews` ?


      • The problem in my case, was the project type. It won’t work if it’s not a Razor Class Library, despite having all the correct imports… I tryed adding this behavior to my current project, which uses Class Library (.NET Core), and that’s why GetView and FindView didn’t work.


  8. Hi! Thank you so much for this.
    I have an old Asp.Net MVC application which I want to add beautiful email templates too but since your walk through is for .net core is there a way for me to adapt it to my project.
    Thanks in anticipation.


  9. Hi Scott!
    Great post!
    The only thing I want to ask, are there any possible performance issues, having 500+ of email?
    Should I think on replacing services.AddScoped to singleton, or caching the template somehow?
    What will be the most expensive operation in your solution and how to speed it up?
    Thanks a lot!


    • Hey Danyl – you should be able to make it a Singleton in theory, but I haven’t tried it. As far as performance, I would assume making it a Singleton is pretty negligible, to construct this since there’s not much going on, but I would benchmark it if that matters to your scenario.

      I would assume the slowest part will be generating the HTML from the Razor template, but not much you can really do there since that logic happens inside the RazorViewEngine from ASP.NET Core. This is definitely one of those things where you are trading off less performance for improved developer productivity and long-term maintenance. So if your situation requires performance, then you may have to re-evaluate that trade off and just deal with housing the HTML logic in strings or something rather in Razor.

      I would just try the 500 emails at once though and set a baseline and see if that baseline is good enough for your scenario.


  10. I’m a newbie trying to follow your steps and it seems that some of your steps are missing, like maybe a screenshot is not rendering. You say:

    Add the following code:

    3. Add an EmailButton.cshtml file
    4. Add the following code:



      • Randy – no problem! Was just circling back to this and glad to see all is well. Curious if there’s anything I can do to make them not show up as false positives for ads… if you have any ideas let me know! Thanks.


  11. I’m trying to render a razor view from a aspnetcore 2.2 BackgroundService. Essentially I have a service sleeping in the background that wakes up and sends out emails of various types: Appointment Reminders, Reports to stake holders etc, etc.

    Your code works great until I try to render a view that has TagHelpers in it. When the engine tries to resolve the tag helpers it throws an ArgumentOutOfRange exception.

    I think the problem is that the HttpContext that is created in your code has no routing information in it, and the TagHelper requires that routing info to translate ‘asp-controller’ and ‘asp-action’ into html.

    I have seen other people use IHttpContextAccessor to get a legit context, but naturally the returned context is always null in the context of a Background Service (Makes sense to me, unless I’m missing something!?).

    Any thoughts on how to solve this? I hate to hardcode links in every view that I could potentially want to render to a string.

    Here is the stacktrace:
    at System.ThrowHelper.ThrowArgumentOutOfRange_IndexException()
    at System.Collections.Generic.List`1.get_Item(Int32 index)
    at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.get_Router()
    at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.GetVirtualPathData(String routeName, RouteValueDictionary values)
    at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.Action(UrlActionContext actionContext)
    at Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper.Process(TagHelperContext context, TagHelperOutput output)
    at Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
    at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.d__0.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at AspNetCore.Views_Shared__email_Layout2.<b__35_1>d.MoveNext() in C:\Workspace\GroomShop\GroomShop.Web\Views\Shared\_email_Layout2.cshtml:line 144


  12. To avoid the exception being generated in the above message, I have modified GetActionContext() to have a Router in its collection as seen below. This solves the exception problem but unfortunately now the tag-helpers incorrectly resolve to href=””. Hopefully someone has seen this before and has a recommendation / solution?

    private ActionContext GetActionContext()
    var httpContext = new DefaultHttpContext
    RequestServices = this._serviceProvider,

    var attrRouter = this._serviceProvider.GetRequiredService();

    var rd = new RouteData();
    //rd.Values.Add(“controller”, “Email”);
    //rd.Values.Add(“action”, “AppointmentReminder”);

    var result = new ActionContext(httpContext, rd, new ActionDescriptor());

    return result;


  13. i am getting an invalid operation exception : InvalidOperationException: The model item passed into the ViewDataDictionary is of type ‘HTMLEmails.Views.Emails.ConfirmAccount.ConfirmAccountEmailViewModel’, but this ViewDataDictionary instance requires a model item of type ‘NetCoreApp.Models.LoginViewModel’. although i did every thing exactly the same.
    using asp.net core 2.2


    • Problem solved!
      there was a conflict between the view start of the original project and the view start of the HTML emails project, moving the latter view start to the emails folder solved the problem.

      Thanks for the great post!


  14. THANK YOU!!!
    I’ve always thought that it had to be “easy” to get Razor views to work with server side rendering to a string, but I have had one heck of a time finding a way to do this. In my opinion this needs to be written up on MSDN as the “official” way to do templating in .NET Core. I’m not using this for emails but for HTML report to PDF generation. It’s rather easy to take a HTML document and go to PDF but the missing link I had was being able to make the HTML on the server side and handing it off to the PDF renderer. This solves that problem in such an elegant way!


    • Hey Mike – I really appreciate the comment. That’s a great point about HTML => PDF and is a great use case for this type fo thing as well. Thanks again for taking the time to leave the comment, I really appreciate it.


  15. This is very helpful and works great for sending HTML emails.

    I’m trying a similar approach for plain text emails (actually multi-part HTML/plain text) by setting up a second RazorViewEngine for the text version that automatically looks for .text.cshtml versions of the views for the plain-text versions.

    Everything is working well except there seems to be no way to create a RazorViewEngine that isn’t geared towards HTML as an HtmlEncoder is required in its constructor. As a result, everything in my plain-text views must be wrapped with Html.Raw() or new HtmlString() to avoid being HTML-encoded, otherwise characters like + in model values end up escaped as HTML entities in the plain text part of the email. Raw/new HtmlString works, but it really clutters up the plain-text Razor views and it seems kinda redundant to encode only to then unencode the model values. Implementing a custom HtmlEncoder seems challenging and likely to be error-prone as well because a lot of the encoding helper classes that the default HtmlEncoder uses are internal.

    I would be interested to hear if anyone has any other approaches for using Razor with plain-text templates.

    Liked by 1 person

  16. Hey Scott thank you for this tutorial its the best solution i found so far and it works like a charm the only issue is that i cant seem to find a way to use localization (po or resx) for the RazorHtmlEmail.RazorClassLib. Im not a .net pro but ive been searching for hours, a link to a tutorial could be useful. Stay awesome Scott!


  17. Hi Scott. Thanks so much for this blog, it solves a multitude of problems in an elegant way. However, I’m struggling to get a way to embed links to graphics inside the emails. The IUrlHelper seems to be generated from the ActionContext and this is devoid of any route data. I’ve been struggling to find a way to upgrade this method to include a valid router but have not yet found a way. Do you have a solution to this?


  18. Great tutorial! Is it possible to get the rendered markup out without it being escaped? The output for tags like looks like this <h1>.


  19. Hi Scott,
      I am trying to implement the email service with templates in Razor with ModelView, however when trying to load the Model by its method, I get the error: “Index was out of range. Must be non-negative and less than the size of the collection . \ r \ nParameter name: index “.
      Can you help me understand what this error could be, as it seems to me that he is not able to load the model in the view.

    var viewContext = new ViewContext (
                            new ViewDataDictionary (
                                metadataProvider: new EmptyModelMetadataProvider (),
                                modelState: new ModelStateDictionary ())
                                Model = model
                            new TempDataDictionary (
                            new HtmlHelperOptions ());

      The exception is giving this line marked with -> await view.RenderAsync (viewContext);


  20. I have seen that others also have said that had i similar problem, with the render not finding the view.
    But i did not found a single solution to this problem.

    You said that it was possible to use a asp.net core 3 library as a .RazorClassLib, but does not seem to work for me.

    I have downloaded your project and looked at the diffrence between your project and mine.

    I could find two ‘major’ differences:
    This first one is that your are still using MailKit(2.4.1) instead of NETCORE.MailKit(2.0.2) in your github repo.

    And the second one is that you have an additional framework in your RazorCallsLib; you have the Microsoft.AspNetCore.App. (I only have the Microsoft.NETCore.App)


    • For some odd reason i can not edit or remove my comment, here is my edit:

      I have seen that others also have said that they had a similar problem, with the render not finding the view.
      But i did not found a single solution to this problem.



      I could only find two ‘major’ differences:

      And the second one is that you have an additional framework in your RazorCallsLib; your project has the Microsoft.AspNetCore.App. (I only have the Microsoft.NETCore.App)


  21. Hello Scott,
    Thank you for a good solution to render emails! Unfortunately I don’t quite get it to work. I downloaded your two libraries (RazorHtmlEmail.Common and RazorHtmlEmails.RazorClassLib) and added them to my project so the code should be correct. But when I try to reference it in my original project it does not recognize the names (CS0246: The type or namespace name ‘RazorHtmlEmails’ could not be found (are you missing a using directive or an assembly reference?)

    Here is a small snippet of my code where the error occurs: https://freeimage.host/i/error.J0CegS

    I noticed that your placeholder project for using the libraries has the same name (RazorHtmlEmails), could this be why my project does not find them?

    My project uses .NET Core 3.0


    • Oscar, the latest examples show .NET Core 3.1. I would suspect that could be your problem if you have project references to the other two projects. .NET Core 3.0 dropped out of support in March so I would recommend upgrading to 3.1 anyways, and it’s pretty painless. Let me know if that helps!


  22. This worked like a charm once I created my Razor Class Library correctly, thank you!

    A note for anyone creating a Razor Class Library with Visual Studio 2019. On the last screen before it is created you have to make sure you select the “Support pages and views” checkbox for this to work. It isn’t checked by default and the proper dependencies for the RazorViewToStringRenderer to work correctly will not be included if it isn’t checked.

    Liked by 1 person

    • Thanks for letting me know Keith! I have updated the tutorial to reflect this. I think this may have been a recent addition with the Blazor WASM release, because I haven’t seen this in 3.1 until now.


  23. I want to make it work for dynamic model since I wont be able to create separate ViewModels for all emails. When I changed TModel to dynamic, this line
    view.RenderAsync(viewContext) threw
    An exception of type Microsoft.CSharp.RuntimeBinder.RuntimeBinderException occurred in System.Private.CoreLib.dll but was not handled in user code
    object’ does not contain a definition for Name


Leave a Reply


WordPress.com Logo


Google photo


Twitter picture


Facebook photo


Connecting to %s