The System.Net.Mail
namespace in .NET provides the necessary classes to send emails via SMTP. This namespace is part of the .NET Framework and is also available in .NET Core and .NET 5+ under the System.Net.Mail
assembly. Below is a tutorial on how to send an email using System.Net.Mail
in a .NET Core application.
* You must first create an actual email user on our SmarterMail Email Servers to authenticate and send email: How do I create an Email User? - Knowledgebase - Adaptive Web Hosting
1. Setup Your .NET Core Project
Ensure you have a .NET Core project set up. You can create a new console application using the .NET CLI:
dotnet new console -n EmailSenderApp
cd Email
SenderApp
2. Add Necessary Using Directives
You'll need to include the System.Net.Mail
namespace at the top of your code file. This namespace provides the SmtpClient
, MailMessage
, and other related classes.
using System;
using System.Net;
using System.Net.Mail;
3. Creating and Sending an Email
Here's an example of how to set up and send an email:
class Program
{
static void Main(string[] args)
{
// Define the SMTP server and credentials
string smtpServer = "smtp.example.com";
int smtpPort = 25;
string smtpUser = "[email protected]";
string smtpPass = "your-email-password";
// Create a new MailMessage object
MailMessage mail = new MailMessage();
mail.From = new MailAddress(smtpUser, "Your Name");
mail.To.Add(new MailAddress("[email protected]", "Recipient Name"));
mail.Subject = "Test Email Subject";
mail.Body = "Hello, this is a test email sent from a .NET Core application.";
// Optionally, you can set the mail body format as HTML
// mail.IsBodyHtml = true;
// Configure the SMTP client
using (SmtpClient smtp = new SmtpClient(smtpServer, smtpPort))
{
smtp.Credentials = new NetworkCredential(smtpUser, smtpPass);
smtp.EnableSsl = true; // Enable SSL/TLS
try
{
// Send the email
smtp.Send(mail);
Console.WriteLine("Email sent successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Error sending email: {ex.Message}");
}
}
}
}
4. Key Components Explained
- MailMessage: Represents the email to be sent. You set properties like
From
,To
,Subject
, andBody
. - SmtpClient: Handles the connection to the SMTP server and sends the email. It requires the server address, port, and optionally credentials for authentication.
- NetworkCredential: Used for specifying the username and password for the SMTP server.
5. Important Considerations
- SMTP Server and Port: Replace
"smtp.example.com"
with your actual SMTP server address issued to you in your Welcome Email. When sending email from from Script use our SSL/TLS secure port of 25. - Security: Always use secure connections (
EnableSsl = true
). For production, avoid hardcoding sensitive information like passwords; use environment variables or secure storage solutions. - Error Handling: Implement robust error handling. In the example, we catch and display exceptions that may occur when sending the email.