"Knowledge has to be improved, challenged, and increased constantly, or it vanishes."

System.Net.Mail.SmtpClient is not recommended anymore; what is the alternative?

For years, I have been using System.Net.Mail namespace to send email from my ASP.Net applications. Recently one of my friend asked my assistance in troubleshooting the email delivery issues from a newly deployed application. It was interesting that the same deployed code was sending email with the same configuration settings. However, I noticed, the test environment is Windows and the Production is Ubuntu. I wanted to understand is there any difference, do we need to add any extra parameters when using Linux, So I went into the SmtpClient documentation, that was used by the developer to send the Email.

For years, .Net developers used the System.Net.Mail and the SmtpClient class to send Email Messages from .Net Applications. When I decided to look in to the application to see some instructions particularly for Linux platform, I was surprised to see the following in the documentation

“The SmtpClient type is obsolete on some platforms and not recommended on others;”

The System.Net.Mail.SMTPClient class is not recommened to use in new applications, though in some applications it still works. In the remarks section of the documentation, It clearly states the reason.

clip_image002[4]

The documentation suggest to use MailKit, a personal library written by https://github.com/jstedfast. Great, MailKit is based on MimeKit, another project of the same author. It is a great honour for jsteadfact to get his personal library recognized by Microsoft and is officially recommends this library to send email from .Net Core applications.

About MailKit

MailKit is a .Net Foundation project. You may understand more about .Net Foundation here. https://dotnetfoundation.org/about/who-we-are

Sending Email from .Net Core using MailKit

In this article, I am going to show you, how to send email from ASP.Net core using Mail Kit. We will be using ASP.Net Core 7 and M365 (Exchange Online), to send the email.

I created an ASP.Net Core Application, I will be sharing the Github link of the project at the end. For the purpose of this article, I am going to read From address and To address from the AppSettings. In real life, you may read these from the database as per your application requirements.

See the following AppSettings.Json file


{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "EmailSettings": {
    "FromName": "My Name",
    "FromEmail": "myemail@example.com",
    "ToName": "Receiver Name",
    "ToEmail": "receiver@example.com",
    "Subject": "Email Message",
    "Username": "username",
    "Password": "password",
    "Host": "smtp.example.com",
    "Port": 25
  },
  "AllowedHosts": "*"
}

See the screenshot of the AppSettings once I modified the values.

In order to use MailKit in your code, you need to add a reference to the MailKit Package. You can do it by any of the following methods.

In the package manager console, you may use the following command

Install-Package MailKit

Or in Nuget Package Manager, search for MailKit and install the package.

clip_image006[4]

Now to send Email, I created a Form, as follows.


    <form method="post">
        <div class="p-3">
            Enter the Message: <textarea asp-for="Message" class="w-auto"> </textarea>
        </div>

        <div>
            <button >Click to Send Email</button>
        </div>
    </form>

First thing you need to add references to the required packages.


using MailKit.Net.Smtp;
using MimeKit;

Now see the OnPost handler method


        public void OnPost()
        {
            //Create a MimeMessage            
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress(Configuration["EmailSettings:FromName"], Configuration["EmailSettings:FromEmail"]));
            email.To.Add(new MailboxAddress(Configuration["EmailSettings:ToName"], Configuration["EmailSettings:ToEmail"]));
            email.Subject = Configuration["EmailSettings:Subject"];
            email.Body = new TextPart(MimeKit.Text.TextFormat.Html)
            {
                Text = Message
            };
            //MimeMessage is ready, now send the Email.
            using (var client = new SmtpClient())
            {
                client.Connect(Configuration["EmailSettings:Host"],Configuration.GetValue("EmailSettings:Port"), false);
                client.Authenticate(Configuration["EmailSettings:Username"], Configuration["EmailSettings:Password"]);
                ViewData["ResponseMessage"] += client.Send(email);
                client.Disconnect(true);
            }
        }

The code is similar to what you see in SmtpClient class. First you create a MimeMessage object that represent the Email Message. You specify the From, To, Subject, Body and other parameters. Then create an instance of MailKit.Smtp.Net.SmtpClient class to perform connect, authenticate and send operations. As you may notice, I am storing the response message to ViewData, so that I can display it to the users. You may store the parse it, store it in your log files or in database and reconcile in case of audit requirements.

See the following screenshot of Email Sending Page.

clip_image008[4]

See the Email Message received.

clip_image010[4]

Summary

Once the developer updated the code to use MailKit, suddenly the emails started delivering. Shifting to MailKit is relatively easy from System.Net.Mail.SmtpClient. With small changes, your code can be easily compatible with modern standards. We have upgraded all our existing code base to ensure System.Net.Mail classes are replaced with MailKit classes. It is fairly an easy exercise, and now all our projects are migrated with MailKit.

Source Code

The source code used in this article can be downloaded from the below link

https://github.com/sreejukg/SendEmail/tree/main/SendMailProject

Happy Coding!

9 Comments

  • VTI <a href="https://www.vcaretechnicalinstitute.com/ rel="dofollow">Python training institute laxmi nagar </a > is an independent non-profit project venture set up, run, and managed by VCT, to promote the Python training institute laxmi nagar, train a new generation of Python programmers, and support professional careers in programming in Python and related technologies. In line with the strategic goals associated with the enhancement and development of careers in Python programming, VTI Programming Institute provides an independent global framework for curriculum development, skills assessment, and <a href="https://www.vcaretechnicalinstitute.com/ rel="dofollow"> Python programming </a > high-stakes examinations.
    The Most popular online & Offline platforms that offer Python Training courses Is Vcare Technical Institute.
    website - www.vcaretechnicalinstitute.com
    Location - E-7,101 Pradhan ji complex near Jawahar park Laxmi Nagar
    Call on - 8319004365



  • VTI <a href="https://www.vcaretechnicalinstitute.com/ rel="dofollow">Python training institute laxmi nagar </a > is an independent non-profit project venture set up, run, and managed by VCT, to promote the Python training institute laxmi nagar, train a new generation of Python programmers, and support professional careers in programming in Python and related technologies. In line with the strategic goals associated with the enhancement and development of careers in Python programming, VTI Programming Institute provides an independent global framework for curriculum development, skills assessment, and <a href="https://www.vcaretechnicalinstitute.com/ rel="dofollow"> Python programming </a > high-stakes examinations.
    The Most popular online & Offline platforms that offer Python Training courses Is Vcare Technical Institute.
    website - www.vcaretechnicalinstitute.com
    Location - E-7,101 Pradhan ji complex near Jawahar park Laxmi Nagar
    Call on - 8319004365



  • Is it not System.Web.Mail that is obsolete not System.Net version

  • DumpsWrap offers Scaled Agile SAFe 6 Agilist - Leading SAFe (SA) (6.0) real exam questions and practice test engine with real questions and verified answers. Try SAFe 6 Agilist - Leading SAFe (SA) (6.0) exam questions for free. You can also download a free PDF demo of Scaled Agile SAFe 6 Agilist - Leading SAFe (SA) (6.0) exam. Our SAFe 6 Agilist - Leading SAFe (SA) (6.0) Combo Package for which includes PDF (Printable Format) and Testing Engine (Works on Windows and MAC) which ensures you to go through all certification topics and provides you ultimate satisfaction to pass your exam in your first attempt.

  • Entrance to direct web slots, easy to break, no minimum.

  • learn to migrate from hcl notes to outlook

  • Find creative ideas that enhance your business growth.

  • As far as it looks good.

  • Hello everyone! Yesterday evening, I was browsing for entertainment online and came across katsubet casino https://katsubet.casinologinaustralia.com/ . I couldn’t believe how much fun it was—and I even won some money! If you’re after a great gaming experience with the potential for winnings, I’d definitely recommend katsubet casino.

Add a Comment

As it will appear on the website

Not displayed

Your website