Streamline Your Email Sending Process: Learn The Best way To Send Emails In ASP.NET Core Web API
We won’t just scratch the surface, though. We’ll dive into utilizing an SMTP server to send emails, and we’ll even use Ethereal for testing the email sending process. Plus, we’ll show you how to define an HTML template to send emails in ASP.NET Core Web API.
To send an email in ASP.NET Core Web API, we will use an interface and a class to define a method for sending an email. Through dependency injection, we will call that method in an API controller.
So what are you waiting for? Keep reading to learn how to send emails like a pro in ASP.NET Core Web API!
Step 1
Using the NuGet Package Manager Console, install the MailKit package.
MailKit is a Cross Platform client library for sending email on multiple platforms, including Windows, Mac OS, Linux, and mobile devices, through .NET.
Step 2
add an IEmailSender interface, define a method called SendEmail with two parameters: ‘toEmail’ for the recipient’s email address and ‘subject’ for the email subject.
namespace Sending_Emails_in_Asp.Net_Core
{
public interface IEmailSender
{
void SendEmail(string toEmail, string subject);
}
}
Step 3
Create a class called EmailSender and have it inherit from the IEmailSender interface. Implement the SendEmail method of the IEmailSender interface in the EmailSender class as follows.
using System.Net.Mail;
using System.Net;
using System.Text;
namespace Sending_Emails_in_Asp.Net_Core
{
public class EmailSender : IEmailSender
{
public void SendEmail(string toEmail, string subject)
{
// Set up SMTP client
SmtpClient client = new SmtpClient("smtp.ethereal.email", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("abby.wehner53@ethereal.email", "djgwPz8DPss78aakBv");
// Create email message
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("abby.wehner53@ethereal.email");
mailMessage.To.Add(toEmail);
mailMessage.Subject = subject;
mailMessage.IsBodyHtml = true;
StringBuilder mailBody = new StringBuilder();
mailBody.AppendFormat("<h1>User Registered</h1>");
mailBody.AppendFormat("<br />");
mailBody.AppendFormat("<p>Thank you For Registering account</p>");
mailMessage.Body = mailBody.ToString();
// Send email
client.Send(mailMessage);
}
}
}
First of all we have to setup the SmtpClient . SmtpClient allows sending email using SMTP Server. SMTP is widely used protocol for sending email between TCP/IP system and users.
SmtpClient client = new SmtpClient(“smtp.gmail.com”, 587);
In this line we created a new instance of the SmtpClient class and sets the host name and port number for the Gmail SMTP server. “smtp.gmail.com” is the SMTP server hostname for Gmail, and 587 is the port number to use for secure SMTP (SMTPS).
client.EnableSsl = true;
This line sets the EnableSsl
property of the SmtpClient
instance to true
. This means that the client will use SSL (Secure Sockets Layer) encryption to secure the communication between the client and the server.
client.UseDefaultCredentials = false;
This line sets the UseDefaultCredentials
property of the SmtpClient
instance to false
. This means that the client will not use the default credentials of the current user to authenticate with the SMTP server.
client.Credentials = new NetworkCredential(“your-email-address@gmail.com”, “your-email-password”);
This line sets the Credentials
property of the SmtpClient
instance to a new instance of the NetworkCredential
class, which contains the email address and password of the account that will be used to send the email messages. In this example, replace "your-email-address@gmail.com"
with the actual email address and "your-email-password"
with the actual password for that email account.
Once you have set up the SmtpClient
instance with the appropriate settings, you can use it to send email messages using the Send
method of the SmtpClient
class.
MailMessage mailMessage = new MailMessage();
This line creates a new instance of the MailMessage
class, which represents an email message.
mailMessage.From = new MailAddress(“your-email-address@gmail.com”);
This line sets the From
property of the MailMessage
instance to a new instance of the MailAddress
class, which specifies the email address of the sender. In this example, replace "your-email-address@gmail.com"
with the actual email address of the sender.
mailMessage.To.Add(toEmail);
This line adds an email address specified in the toEmail
variable to the To
property of the MailMessage
instance, which specifies the email address of the recipient.
mailMessage.Subject = subject;
This line sets the Subject
property of the MailMessage
instance to the value of the subject
variable, which specifies the subject of the email message.
mailMessage.IsBodyHtml = true;
This line sets the IsBodyHtml
property of the MailMessage
instance to true
, which indicates that the email message body should be formatted using HTML.
StringBuilder mailBody = new StringBuilder();
mailBody.AppendFormat(“<h1>User Registered</h1>”);
mailBody.AppendFormat(“<br />”);
mailBody.AppendFormat(“<p>Thank you For Registering account</p>”);
mailMessage.Body = mailBody.ToString();
These lines create a new StringBuilder
instance called mailBody
, and use it to construct an HTML-formatted email message body. The AppendFormat
method is used to add various HTML elements, such as a heading and paragraph, to the mailBody
instance. Finally, the ToString
method is called on mailBody
to convert it to a string, which is assigned to the Body
property of the MailMessage
instance.
client.Send(mailMessage);
This line sends the email message represented by the MailMessage
instance using the SmtpClient
instance that was set up in the previous code block. The Send
method takes the MailMessage
instance as a parameter.
Step 4
Now add Dependency Injection in program.cs class as follows we will Explain Dependency Injection in another article in detail.
builder.Services.AddTransient<IEmailSender,EmailSender>();
This code is registering a transient email sending service with the dependency injection container, which can be used throughout the application wherever an instance of IEmailSender
is required.
Step 5
Now Inject IEmailSender Interface in Constructor as follows
private readonly IEmailSender _emailSender;
public UserController(IEmailSender emailSender)
{
_emailSender = emailSender;
}
this constructor is initializing a private field called _emailSender
with an instance of a class that implements the IEmailSender
interface. This allows the UserController
class to use the _emailSender
field throughout its implementation, without needing to know exactly what implementation of IEmailSender
it is using. By using constructor injection in this way, the code becomes more modular and easier to test.
Step 6
Now call the Method as follows
public ActionResult AddNewUser(User user)
{
_commonRepository.Insert(user);
var result=_commonRepository.SaveChanges();
_emailSender.SendEmail(user.Email, "User Regitered");
if (result > 0)
{
return CreatedAtAction("GetUser", new { id = user.id }, user);
}
return BadRequest();
}
We can also use Ethreal for testing the Email.
You have to create an ethreal account and change your email setting According to Ethreal Now after hitting the service check your ethreal mail box.