Sending Email in C# (.NET): System.Net.Mail Library

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Sending Email in C# (.NET): A Complete Guide to System.Net.Mail

In modern .NET platform development, the task of sending emails is handled by the standard System.Net.Mail library. This built-in tool does not require installing additional NuGet packages and provides a flexible API for creating and sending mail messages via an SMTP server. In this article, we will thoroughly examine all key components of the library, review code examples, error handling, and best practices.



Main Library Classes

The System.Net.Mail library includes three main classes:

  • SmtpClient — responsible for connecting to the SMTP server and sending messages.
  • MailMessage — represents the email itself: subject, body, sender, recipients, attachments.
  • Attachment — allows adding files to the email.


Basic Email Sending Example

Let's consider a simple scenario: sending a text email via the Gmail SMTP server. Note that working with Gmail requires an App Password due to two-factor authentication.

using System;using System.Net;using System.Net.Mail;

class Program{ static void Main() { var fromAddress = new MailAddress("your@gmail.com", "Your Name"); var toAddress = new MailAddress("recipient@example.com", "Recipient"); const string fromPassword = "your_app_password"; const string subject = "Test email from .NET"; const string body = "Hello! This email was sent using C#.";

var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) };

using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); }

Console.WriteLine("Email sent!"); }}


Sending HTML Emails with Attachments

Often you need to send an email in HTML format with attached files. To do this, set the IsBodyHtml = true property and use the Attachments collection.

using (var message = new MailMessage(fromAddress, toAddress)){    message.Subject = "Monthly Report";    message.IsBodyHtml = true;    message.Body = "<h2>Hello!</h2><p>Your report is attached.</p>";

// Add attachment var attachment = new Attachment(@"C:\\reports\\report.pdf"); message.Attachments.Add(attachment);

smtp.Send(message);}


Asynchronous Sending (async/await)

For non-blocking sending in modern applications, use SendMailAsync. This is especially important in web applications (ASP.NET Core) and desktop programs with a UI.

public async Task SendEmailAsync(){    using (var message = new MailMessage(fromAddress, toAddress)    {        Subject = "Async Sending",        Body = "Email sent asynchronously"    })    {        await smtp.SendMailAsync(message);    }}


Exception Handling

When working with mail servers, errors can occur: invalid credentials, timeouts, DNS issues. Always wrap the sending in a try-catch block.

try{    smtp.Send(message);    Console.WriteLine("Successfully sent.");}catch (SmtpException ex){    Console.WriteLine($"SMTP error: {ex.StatusCode} - {ex.Message}");}catch (Exception ex){    Console.WriteLine($"General error: {ex.Message}");                    

Recommendations