System.Net.Mail Namespace
Namespace
Provides classes used for sending electronic mail (e-mail) messages.
The System.Net.Mail namespace contains classes that allow you to construct, send, and manage e-mail messages programmatically. This includes capabilities for specifying sender and recipient addresses, subject lines, message bodies (in plain text or HTML), attachments, and even mail server settings.
This namespace is essential for applications that need to send notifications, confirmations, reports, or any other form of e-mail communication.
Classes
-
MailAddress
Represents an individual e-mail address. You can specify the display name and the address itself.
-
MailMessage
Represents an e-mail message. This is the core class for constructing an e-mail, including sender, recipients, subject, body, and attachments.
-
SmtpClient
Provides a client for sending e-mail using the Simple Mail Transfer Protocol (SMTP).
-
Attachment
Represents an attachment in an e-mail message.
-
MailPriority
Specifies the priority of an e-mail message.
-
DeliveryNotificationOptions
Specifies options for delivery notifications for an e-mail message.
Getting Started
Here's a basic example of how to send an e-mail using System.Net.Mail:
using System.Net;
using System.Net.Mail;
// Create the mail message
MailMessage mail = new MailMessage();
mail.From = new MailAddress("sender@example.com");
mail.To.Add("recipient@example.com");
mail.Subject = "Test Email";
mail.Body = "This is the body of the test email.";
// Create an SMTP client
SmtpClient smtp = new SmtpClient("smtp.example.com"); // Replace with your SMTP server
smtp.Port = 587; // Default for TLS
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("sender@example.com", "your_password"); // Replace with your credentials
try
{
smtp.Send(mail);
Console.WriteLine("Email sent successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to send email. Error: {ex.Message}");
}