Complete steps for sending Email in Asp. Net Core

  • 2021-11-29 06:37:18
  • OfStack

Preface

In project development, it is often necessary to send Email. In ASP. NET Core, you can use MailKit to send Email. MailKit is an open source client library, which can be used on Windows, Linux or Mac. This article will discuss the implementation in ASP. NET Core.

Installing MailKit

To use MailKit, you can install it using the NuGet package manager visual interface in Visual Studio 2019, or enter the following command from the NuGet package manager console command line:


Install-Package NETCore.MailKit

After the installation is complete, introduce the following command space into the code.


using MailKit.Net.Smtp;
using MimeKit;

Basic information for configuring Email

The following code snippet shows the details of configuring email in the appsettings. json file.


"NotificationMetadata": {
 "Sender": "sender_email@gmail.com",
 "SmtpServer": "smtp.gmail.com",
 "Reciever": "receiver_email@yahoo.com",
 "Port": 465,
 "Username": "sender_email_user@gmail.com",
 "Password": "specify your password here"
 }

To be able to implement the NotificationMetadata node mapping in configuration, I defined an NotificationMetadata class with the following code:


 public class NotificationMetadata
 {
  public string Sender { get; set; }
  public string Reciever { get; set; }
  public string SmtpServer { get; set; }
  public int Port { get; set; }
  public string UserName { get; set; }
  public string Password { get; set; }
 }

Next, the NotificationMetadata node is mapped to the NotificationMetadata class in the Startup. ConfigureServices method.


public void ConfigureServices(IServiceCollection services)
{
  var notificationMetadata =
  Configuration.GetSection("NotificationMetadata").
  Get<NotificationMetadata>();
  services.AddSingleton(notificationMetadata);
  services.AddControllers();
}

Generate an EmailMessage message class

Create an EmailMessage class using the following code.


private MimeMessage CreateMimeMessageFromEmailMessage(EmailMessage message)
{
  var mimeMessage = new MimeMessage();
  mimeMessage.From.Add(message.Sender);
  mimeMessage.To.Add(message.Reciever);
  mimeMessage.Subject = message.Subject;
  mimeMessage.Body = new TextPart(MimeKit.Text.TextFormat.Text)
  { Text = message.Content };
  return mimeMessage;
}

Generate the MimeMessage class

The following code shows how to construct an MimeMessage from a custom EmailMessage class.


private MimeMessage CreateMimeMessageFromEmailMessage(EmailMessage message)
{
  var mimeMessage = new MimeMessage();
  mimeMessage.From.Add(message.Sender);
  mimeMessage.To.Add(message.Reciever);
  mimeMessage.Subject = message.Subject;
  mimeMessage.Body = new TextPart(MimeKit.Text.TextFormat.Text)
  { Text = message.Content };
  return mimeMessage;
}

Send Email synchronously with MailKit

In order to finally enable email sending, you need to use the SmtpClient class under the MailKit. Net. Smtp namespace, and the following code shows the specific implementation steps.


using (SmtpClient smtpClient = new SmtpClient())
{
 smtpClient.Connect(_notificationMetadata.SmtpServer,
 _notificationMetadata.Port, true);
 smtpClient.Authenticate(_notificationMetadata.UserName,
 _notificationMetadata.Password);
 smtpClient.Send(mimeMessage);
 smtpClient.Disconnect(true);
}

For convenience, I put the complete send Email code under the DefaultController. Get method.


public string Get()
{
 EmailMessage message = new EmailMessage();
 message.Sender = new MailboxAddress("Self", _notificationMetadata.Sender);
 message.Reciever = new MailboxAddress("Self", _notificationMetadata.Reciever);
 message.Subject = "Welcome";
 message.Content = "Hello World!";
 var mimeMessage = CreateEmailMessage(message);
 using (SmtpClient smtpClient = new SmtpClient())
 {
  smtpClient.Connect(_notificationMetadata.SmtpServer,
  _notificationMetadata.Port, true);
  smtpClient.Authenticate(_notificationMetadata.UserName,
  _notificationMetadata.Password);
  smtpClient.Send(mimeMessage);
  smtpClient.Disconnect(true);
 }
 return "Email sent successfully";
}

Send Email asynchronously with MailKit

Above, we sent Email synchronously. This section looks at how to send Email asynchronously.


using (SmtpClient smtpClient = new SmtpClient())
 {
  await smtpClient.ConnectAsync(_notificationMetadata.SmtpServer,
  _notificationMetadata.Port, true);
  await smtpClient.AuthenticateAsync(_notificationMetadata.UserName,
  _notificationMetadata.Password);
  await smtpClient.SendAsync(mimeMessage);
  await smtpClient.DisconnectAsync(true);
 }

Finally, it is worth noting that MailKit not only supports simple strings, but also supports templates and even can be sent with attachments. I will discuss more features of MailKit with you in the following articles.

Translation link: https://www.infoworld.com/art...

Summarize


Related articles: