Back to: ASP.NET Core Identity Tutorials
Configuring Email Service in ASP.NET Core Identity
In this article, I will discuss Configuring Email Service in ASP.NET Core Identity, i.e., How to Send Email in ASP.NET Core Application. Please read our previous article discussing ASP.NET Core Secret Manager.
What is an Email Service?
An email service in the context of web applications is a mechanism that allows the application to send emails to users programmatically. An Email Service is responsible for managing email communication within an application. This can include sending notifications, confirmations, password reset links, verification emails, newsletters, promotional materials, and more. In web development, email services are typically implemented through an SMTP (Simple Mail Transfer Protocol) server that handles sending these emails from your application. Email Service often supports different providers (Gmail, Outlook, SendGrid, AWS SES, etc.).
Why Email Service in ASP.NET Core Identity?
ASP.NET Core Identity is a membership system that adds login functionality to ASP.NET Core applications. It supports account confirmation, password recovery, and two-factor authentication (2FA), among other features. An Email Service is an integral part of ASP.NET Core Identity for the following reasons:
- User Verification: Sends confirmation emails to verify the user’s email address. This helps reduce spam accounts and verify the identity of a user.
- Password Recovery: If users forget their password, they can reset their passwords via a secure link sent to their registered email. ASP.NET Core Identity sends a link to reset the password via email.
- Two-Factor Authentication (2FA): Sends one-time passwords (OTPs) or security codes via email as part of 2FA.
- Notifications: Sends account-related notifications such as profile updates such as password changes, login from a new device, or account lockout warnings.
To enable these features (like sending confirmation emails, password reset links, Two-Factor Authentication, etc.), ASP.NET Core Identity needs access to an Email Service. By configuring an Email Service, we ensure our application can send out the necessary emails to users. ASP.NET Core Identity functionalities like email confirmation and password reset, 2FA, etc., would be challenging to implement effectively without an email service.
How to Configure Gmail SMTP Settings?
We need to configure several settings to send emails through Gmail’s SMTP server. They are as follows:
- SMTP Server Address: The SMTP server for Gmail is smtp.gmail.com.
- Port: Use SSL (Secure Socket Layer) on port 465. If you’re using TLS (Transport Layer Security), use port 587 instead.
- Authentication: Gmail requires authentication. Also, please make sure 2FA is enabled for your account.
- Username: Your Gmail email address (e.g., your-email@gmail.com).
- Password: Your Gmail account password will not work, and you must create an App Password.
Creating App Password:
Let us first see how we can create the App Password, as the regular password will not work. First, Log in to your Google Account. Then go to Account > Security option as shown in the below image:
Once you click on the Security tab, the following page will open. To generate an App Password, you must have two-factor authentication enabled. In my case, I have already enabled the two-factor authentication, as shown in the below image.
If not enabled, please follow the on-screen steps to enable it. Once enabled, then only you can generate the App password.
Search for App Passwords:
On the google account search bar, type App Passwords and then select the App Passwords link as shown in the image below.
Once you click the App Passwords link, it will open the following page, asking you to enter your App Name. Here, you can give any name to your app. I am giving the name as Dot Net Tutorials and click on the Create button as shown in the below image:
Once you click the Create button, it will open the Generated app password popup, as shown in the image below. Just save the app the app password, which we will use in our application. Please note the 16-character password provided. This password will be used in your application instead of your regular Gmail password.
Set Up SMTP Configuration:
Integrating Gmail’s SMTP with an ASP.NET Core application involves setting up the necessary configurations and implementing email-sending functionality. Let us proceed and understand how to integrate Gmail’s SMTP with an ASP.NET Core application step by step.
Setup Configuration:
Add your SMTP settings to the appsettings.json file in your ASP.NET Core project. So, please add the following configuration to your appsettings.json file:
"EmailSettings": { "MailServer": "smtp.gmail.com", "MailPort": 587, "SenderName": "Your Application Name", "FromEmail": "yourgmail@gmail.com", "Password": "yourAppPassword" }
Replace yourgmail@gmail.com and app password with your actual Gmail ID and app password. Also, give a meaningful sender name.
Create an Email Service
Create a service class in your application to handle email sending. First, create a folder named Services, and inside that folder, create a class file named EmailSenderService.cs and then copy and paste the following code. The following code is self-explained, so please read the comment lines for a better understanding.
using System.Net.Mail; // Namespace for email-related classes like SmtpClient and MailMessage. using System.Net; // Namespace for network credentials and related functionality. namespace ASPNETCoreIdentityDemo.Services { public class EmailSenderService { // Configuration property to access application settings. private readonly IConfiguration _configuration; // Constructor that injects the configuration dependency. public EmailSenderService(IConfiguration configuration) { // Save the configuration object for later use. _configuration = configuration; } // Method to send an email asynchronously. public Task SendEmailAsync(string ToEmail, string Subject, string Body, bool IsBodyHtml = false) { // Retrieve the mail server (SMTP host) from the configuration. string? MailServer = _configuration["EmailSettings:MailServer"]; // Retrieve the sender email address from the configuration. string? FromEmail = _configuration["EmailSettings:FromEmail"]; // Retrieve the sender email password from the configuration. string? Password = _configuration["EmailSettings:Password"]; // Retrieve the sender's display name from the configuration. string? SenderName = _configuration["EmailSettings:SenderName"]; // Retrieve the SMTP port number from the configuration and convert it to an integer. int Port = Convert.ToInt32(_configuration["EmailSettings:MailPort"]); // Create a new instance of SmtpClient using the mail server and port number. var client = new SmtpClient(MailServer, Port) { // Set the credentials (email and password) for the SMTP server. Credentials = new NetworkCredential(FromEmail, Password), // Enable SSL for secure email communication. EnableSsl = true, }; // Create a MailAddress object with the sender's email and display name. MailAddress fromAddress = new MailAddress(FromEmail, SenderName); // Create a new MailMessage object to define the email's properties. MailMessage mailMessage = new MailMessage { From = fromAddress, // Set the sender's email address with display name. Subject = Subject, // Set the email subject line. Body = Body, // Set the email body content. IsBodyHtml = IsBodyHtml // Specify whether the body content is in HTML format. }; // Add the recipient's email address to the message. mailMessage.To.Add(ToEmail); // Send the email asynchronously using the SmtpClient instance. return client.SendMailAsync(mailMessage); } } }
Code Explanations:
- Dependency Injection: The IConfiguration object is injected into the constructor, allowing the class to access configuration settings.
- Configuration Retrieval: Various email-related settings like MailServer, FromEmail, Password, Port, and SenderName are retrieved from the app’s configuration file (e.g., appsettings.json).
- SMTP Setup: SmtpClient is configured with the SMTP server details, credentials, and SSL settings for secure communication.
- MailAddress Usage: MailAddress is used to include both the email address and the sender’s display name.
- MailMessage: This object represents the email, including the sender, recipient, subject, body, and body format.
- Asynchronous Sending: SendMailAsync ensures the email is sent asynchronously, preventing blocking of the calling thread.
Register Email Service into Dependency Injection Container:
In Program.cs, register your email service as follows:
builder.Services.AddTransient<EmailSenderService>();
You can send emails from your ASP.NET Core in many ways. The simplest way is to use Gmail and SmtpClient from the System.Net.Mail namespace.
In the next article, I will discuss Email Confirmation in ASP.NET Core Identity. In this article, I explain How to Configure Email Service in ASP.NET Core. I hope you enjoy this article, Configuring Email Service in ASP.NET Core.