This guide provides a C# code example for sending emails from your ASP.NET website using the local mail server. This is commonly used for contact forms, order confirmations, or system notifications.
info@mysite.com, the email must be sent from info@mysite.com.You can use the built-in System.Net.Mail namespace to send messages. Copy and adapt the snippet below:
using System.Net;
using System.Net.Mail;
// Configuration Variables
string smtpHost = "smtp.yourdomain.com";
int smtpPort = 25; // Try port 26 if 25 doesn't work
string smtpUser = "info@yourdomain.com"; // Full email address
string smtpPass = "YourPassword";
string toAddress = "recipient@external-domain.com";
// Create the message
// IMPORTANT: The 'From' address must match the 'smtpUser'
MailMessage msg = new MailMessage(smtpUser, toAddress);
msg.Subject = "Test Subject";
msg.Body = "This is a test email sent from ASP.NET";
msg.IsBodyHtml = true;
// Configure the SMTP client
SmtpClient client = new SmtpClient(smtpHost, smtpPort);
client.UseDefaultCredentials = false;
client.EnableSsl = false; // Local SMTP usually does not require SSL
client.Credentials = new NetworkCredential(smtpUser, smtpPass);
try
{
// Send the message
client.Send(msg);
}
catch (Exception ex)
{
// Handle errors (log them or display to user)
// Response.Write("Error: " + ex.Message);
}
smtpPort from 25 to 26.