First we will want to create a couple projects, one will be the main project that sends emails called Api the other being a project for templates we will simple call Templates.
To start we will create an ASP.NET Core 2.2 Web Application with a Project Type of Web API and call it Api.
Next we will want to create another project called Templates by going to a new ASP.NET Core 2.2 Web Application and selecting Razor Class Library in the Project Type. This project type will allow us to create Razor Pages for our email rendering.
Once the Razor Project is created we will want to add a few directories to it to help organize the code.
Create directory called Views
Inside Views create a directory called Shared
Inside Views create a directory called Emails
Inside Emails create a directory called HelloWorld
Create a directory called ViewModels
Lastly for the project setup we will want to add a reference to the Templates project in our Api project.
View Model Creation
The full code for these files is available on github so feel free to go over there and copy/paste as needed. To keep this short I will only show the import contents of the files.
To get started we will want to create a couple files in the ViewModels directory.
This is a reusable button to display in the email.
This is going to contain any dynamic variables you would like to use in the HelloWorld email template.
Email Template Creation
In the Shared directory create the following Razor Pages.
This file shows how we import the view model we would like to use and the properties available on that model.
We will want to create two different types of layouts one for HTML and one for text. The content of the files is available on github.
Creating the Specific Email Template
Finally we can create the specific email we would like to send in the Views/HelloWorld directory.
This class is what does a lot of the magic for us. It will use the Razor engine to find the view we specify and build a rendered version of it to be returned as a string. This is what glues all these files together to build the email to be sent.
Sending the Email
The final step to all of this is to send the email off. To do this we will create a simple endpoint that will call the RazorViewToString class to generate the email content.
In the Api project create a controller called EmailsController.cs and add a simple GET method to send an email. (This is only for testing purposes)
In the send method you will need to replace some of the variables for this to work correctly.
In the Startup.cs we will need to add the following line to the ConfigureServices method.