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.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Material Lite Admin Template
11/14/2024
Focus Admin Dashboard Template
11/18/2024
Stisla Admin Dashboard Template
11/18/2024