How to Send Emails ASP.NET Core 5 Using SMTP

In this tutorial, we will learn How to Send Emails ASP.NET core 5 Web API Application using SMTP. If you want to set up a new ASP.NET Core Multi-tier Project click on this link and if want to configure Identity click on this.

What is SMTP:

SMTP is a “Simple mail transfer protocol” that allows applications to send emails. Like Gmail, office365, live, etc.

Tools:

Visual Studio Community 2019

Windows OS

Create A Email Template Class that will hold the data that we want to send our user.

public class EmailTemplate
{
  public string From { get; set; }
  public string To { get; set; }
  public string Subject { get; set; }
  public string Body { get; set; }
}

Now we will create a private method that will convert our email into a sendable message form.

private static MailMessage getMailMessage(EmailTemplate email)
{
    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    mail.Body = email.Body;
    mail.Subject = email.Subject;
    mail.From = new MailAddress("[email protected]");
    mail.To.Add(email.To);
    return mail;
}

Now I will create a method to send emails whenever I have to send an email to anyone I will call this public method. In this method, I will call the above created private method to change my template to a sendable message form.

public bool SendSmtpMail(EmailTemplate data)
{
  try
  {
    MailMessage message = getMailMessage(data);
    var credentials = new NetworkCredential("[email protected]","yourpassword" );
    // Smtp client
    var client = new SmtpClient()
    {
      Port = 587,
      DeliveryMethod = SmtpDeliveryMethod.Network,
      UseDefaultCredentials = false,
      Host = "smtp.office365.com",
      EnableSsl = true,
      Credentials = credentials
      };

    client.Send(message);
    return true;
  }
  catch (Exception e)
  {
    throw e;
  }
}

After converting my message I’m configuring SMTP credentials and after configuring SMTP sending my email.

Now, I will call this email service through my API.

Do not forget to send parameters into your model.

How to Send Emails in ASP.NET

I have got my Email.

In the tutorial, “How to Send Emails ASP.NET core 5 Using SMTP” the Email template model class is standard way to send emails. If you do not want to use this template class you can hard code email body, subject, and to fields. it’s up to you. If you find any difficulty or problem using my code and tutorial, feel free to ask in the comment section or Contact US. I will try to answer as soon as possible.

Happy Coding!

Leave a Reply

Your email address will not be published.