Enabling email verification in ASP.Net Core Identity UI 2.1

Kevin Rodríguez
2 min readJun 12, 2018

--

The new Microsoft.AspNetCore.Identity.UI (2.1.0) package provides an easy way to integrate the identity framework on both new and existing projects by providing an encapsulated, unobstrusive way for adding authentication and authorization, but if you’re either new to the ASP.Net Core 2.1 framework, or upgrading from ASP.Net Core 2.0 you might be wondering how to enable email messages from our new ASP.Net Core Identity UI powered application.

As i’m writing this, there is no documentation on the Microsoft website about how to do this for new projects, but the procedure is pretty simple.

First, we need to create our new ASP.Net Core 2.1 MVC app using individual user accounts…

Then, we will take a small look into the overridable Account\ForgotPassword view, which will contain basic email-sending functionality. We can achieve this by generating an override to the default packaged views by right clicking on the project -> Add -> New scaffolded item… -> Identity -> Identity -> Account\ForgotPassword and then clicking on “Add” after selecting your ApplicationDbContext on the dropdown, then go to:

Areas/Identity/Pages/Account/ForgotPassword.cshtml(Expand)/ForgotPassword.cshtml.cs

As you might notice, the ASP.Net Identity framework now takes advantage of the new Razor UI Class libraries feature on ASP.Net Core 2.1, but most important, you might have noticed it does receive an IEmailSender instance via Dependency Injection.

At this point, if you try to use any of the mail-sending functionality on the default template, no email will be sent.

To fix this, we will create a new Services folder in our project and inside of it, our EmailSender.cs service:

Then, we are going to register our new service into the Dependency Injection bag by adding the following line of code to the Startup.cs class of our project:

services.AddTransient<IEmailSender, EmailSender>()

At this point, you can go ahead and customize your EmailSender.cs class to use either SendGrid (As recommended in Microsoft’s documentation) or your classic good-old SmtpClient from System.Net.Mail (which we will detail below).

Using SmtpClient with ASP.Net Core Identity UI 2.1 to send emails from your MVC application

We will go ahead and modify our EmailSender class to add the following lines of code:

Then, we will configure the smtp settings on our appsettings.json file:

And finally, we need to modify our Startup.cs to use our configuration from the appsettings.json file and passing it as parameters to our EmailSender service:

And that’s it. Now you can send emails by using the new Microsoft ASP.Net Core Identity UI 2.1 framework.

--

--