Sending Emails in C# using MailKit

By FoxLearn 1/8/2025 1:54:12 AM   160
MailKit is a robust open-source .NET library designed for sending and receiving emails. We use it as an alternative to the SmtpClient class from the System.Net.Mail namespace.

It's highly recommended for developers seeking a modern approach, as it supports up-to-date email protocols.

To get started with MailKit, begin by installing it through NuGet.

You can do this in Visual Studio’s Package Manager Console using the following command:

Install-Package MailKit

Once installed, you can use the example C# code below to send your first email.

using System;
using MailKit.Net.Smtp;
using MimeKit;

namespace TestClient
{
    class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                var email = CreateEmailMessage();

                using (var smtp = new SmtpClient())
                {
                    ConnectToSmtpServer(smtp);

                    smtp.Send(email);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }

        private static MimeMessage CreateEmailMessage()
        {
            var email = new MimeMessage
            {
                From = { new MailboxAddress("SenderName", "[email protected]") },
                To = { new MailboxAddress("RecipientName", "[email protected]") },
                Subject = "Hello world",
                Body = new TextPart(MimeKit.Text.TextFormat.Html)
                {
                    Text = "This is a test email sent using C#"
                }
            };

            return email;
        }

        private static void ConnectToSmtpServer(SmtpClient smtp)
        {
            const string smtpServer = "smtp.maileroo.com";
            const int smtpPort = 587;
            const bool useSsl = false;
            const string username = "smtp_username";
            const string password = "smtp_password";

            smtp.Connect(smtpServer, smtpPort, useSsl);
            smtp.Authenticate(username, password);
            smtp.Disconnect(true);
        }
    }
}

Note: The SmtpClient class used in this code is from MailKit, not the one from the System.Net.Mail namespace.

Sending emails in C# .NET via SMTP is simple, whether using the System.Net.Mail namespace or MailKit.