How to send a simple email message [C#]

A simple C# code for sending email.

The System.Net.Mail namespace contains MailMessage and SmtpClient classes, the System.Net namespace contains NetworkCredential class, that we need in order to send the email and specify the user credentials necessary to send authenticated email.

This example will show you how to send a simple email message with authentication using C#.NET:

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

public class MailSender
    public static void SendMail(string from, string to, string subject, string body, 
        string smtpServer, string smtpUsername, string smtpPassword)
        MailMessage message = new MailMessage(from, to, subject, body);
        SmtpClient smtpClient = new SmtpClient(smtpServer);        
        smtpClient.UseDefaultCredentials = false;
        NetworkCredential credentials = new NetworkCredential(smtpUsername, smtpPassword);
        smtpClient.Credentials = credentials;

Applies To

Email server, SMTP

See Also