SmtpClient is obsolete! The new way to send emails from your .NET app…

In the past, when you needed to send emails from a .NET app, the built-in SmtpClient class was typically the most appropriate tool for the job.

However, for some time now the .NET Framework SmtpClient class has not been the recommended option for new development.

In this article, I review how the .NET SmtpClient can be used and explore an alternative way of sending emails using MailKit.

SmtpClient

Prior to looking at MailKit, let’s see what the current deal is with SmtpClient.

If you weren’t already aware that the SmtpClient class has been deprecated, take a look at the following Microsoft Docs link.

https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient

The ‘Remarks’ section of the documentation makes Microsoft’s viewpoint very clear.

We don’t recommend that you use the SmtpClient class for new development because SmtpClient doesn’t support many modern protocols. Use MailKit or other libraries instead. For more information, see SmtpClient shouldn’t be used on GitHub.

So the main reason for not recommending SmtpClient anymore is due to the lack of support for modern protocols; makes sense!

This is especially relevant given the rapid pace at which current security standards are being updated. The need to stay up to date and support the latest protocols is critically important for protecting sensitive data.

Before moving on though, I feel that it’s worthwhile taking a quick look at how the .NET SmtpClient can be utilised, as there may still be cases where you need to use it in existing projects.

Sending a Mail Message

Below is a very basic example of how to send an email using the built-in SmtpClient class.

var message  = new MailMessage();
message.From = new MailAddress("sender@yourdomain.com""Sender Name");
message.To.Add(new MailAddress("recipient@theirdomain.com""Recipient Name"));
message.Subject = "SmtpClient Test";
message.Body    = "Hi from .NET!";
 
var client         = new SmtpClient();
client.Host        = "mail.yoursmtpservice.com";
client.Port        = 465;
client.EnableSsl   = true;
client.Credentials = new NetworkCredential("your_username""your_password");
client.Send(message);

Note that you must change the method parameters e.g. sender@yourdomain.com, mail.yoursmtpservice.com etc. in order for the above code to work correctly.

The classes and methods defined in the above code are pretty straightforward to follow.

First, a MailMessage is defined, which is comprised of a From MailAddress, a To MailAddress, a Subject and a Body.

An SmtpClient object is then created and the Host, Port, SSL flag and Credentials are set and lastly, the email is sent.

Configuration

One of the really nice features of the built-in SmtpClient is its configuration story.

Because the SmtpClient is tightly integrated into the .NET Framework it’s possible to configure the default mail settings from an App.config file, as follows.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.net>
        <mailSettings>
            <smtp from="sender@yourdomain.com">
                <network enableSsl="true" host="mail.yoursmtpservice.com" port="465" 
                         userName="your_username" password="your_password" />
            </smtp>
        </mailSettings>
    </system.net>
</configuration>

Note that I don’t recommend configuring a password in plain text within a config file. I will be covering how to encrypt settings contained within config files in a future article.

With the above in place, you can now simply create a new SmtpClient instance and it will populate its settings using the defaults you have defined automatically.

Following this, you can send an email with very little ceremony, as per the code below.

// Create and configure MailMessage (message).
// ...
 
// Send the message.
var client = new SmtpClient();
client.Send(message);

Note that the client settings can still be overridden, where required, prior to sending a specific message.

For console or service applications which serve a specific purpose and therefore typically only require one set of credentials, the above solution is ideal.

MailKit

MailKit is the library which is specifically mentioned in the Microsoft Docs, so let’s check out how it works.

In regards to dependencies, the latest version of the MailKit NuGet package can be installed into any .NET Framework 4.5+ or .NET Standard 1.3+ project.

MailKit boasts an impressive list of features and supports a wide variety of authentication methods and protocols.

In addition to the broad protocol support, among other things, MailKit alludes to better performance which may be noticeable if you are planning on sending a large volume of emails from your code.

Sending a Mime Message

Here is a very simple example of how to send an email using MailKit.

var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sender Name""sender@yourdomain.com"));
message.To.Add(new MailboxAddress("Recipient Name""recipient@theirdomain.com"));
message.Subject = "MailKit Test";
message.Body    = new TextPart("plain") { Text = "Hi from MailKit!" };
 
using (var client = new SmtpClient())
{
client.Connect("mail.yoursmtpservice.com"587); client.Authenticate("your_username""your_password"); client.Send(message); client.Disconnect(true); }

Note that as per the .NET example you must change the method parameters e.g. sender@yourdomain.com, mail.yoursmtpservice.com etc. in order for the above code to work correctly.

Aside from the slightly different class names, the above code is very similar to the code required when using the .NET SmtpClient.

A MimeMessage object is configured with a From MailboxAddress, a To MailboxAddress, a Subject and a Body TextPart.

The client object is then newed up at the beginning of the using block. A key difference from the standard .NET SmtpClient is that the MailKit SmtpClient stipulates that the Connect method is explicitly called to establish the connection to the mail server. This is a much simpler model than the connection pooling which happens underneath with the .NET SmtpClient.

After connecting, the Authenticate method is called, the message is sent and then the Disconnect method is called to close the connection.

MailGun

If you want to send some test emails from your code, I would like to introduce you to a very neat service called MailGun.

MailGun is “The Email Service for Developers” and it provides a straightforward way to send emails either via the MailGun API or by using SMTP credentials.

You can send emails for free! Up to 5,000 messages per month, 300 per day, to up to 5 authorised email addresses. It’s a great service for testing (and production!).

If you don’t already have access to a suitable SMTP server which you can use for testing, I recommend that you head over to the MailGun sign-up page now and create an account.

After signing up, once you have verified your email address via the email link and have input the SMS verification code, go to the ‘Overview’ sub-section with the ‘Sending’ section of your MailGun account page, then press the ‘Select’ button within the ‘SMTP’ box.

After scrolling down the page a bit, you should be able to see the values of the following settings.

  • SMTP hostname
  • Port
  • Username
  • Default password

Try configuring the client object in your test code with the above settings and input your own email address as the sender and recipient as a starting point.

Note that you may need to check your ‘Spam’ folder after sending a test email.

Closing…

In closing, I think that MailKit is a decent replacement for the .NET SmtpClient. Its API is simple and it should feel familiar for those transitioning from the built-in SmtpClient.

I believe it is valuable to be aware of MailKit and how to use it, especially if you come across a case in the near future where a protocol you need to use is not supported by the .NET SmtpClient.

Lastly, see my sample project on GitHub which includes all of the code from this article.

Until next time, take care.

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.