How to Send an Email via SMTP in C# ?

If you need to send emails via SMTP programmatically using C# , you can use the the SmtpClient class that is defined in the System.Net.Mail namespace.

The MailMessage allows the developers to specify the necessary parameters including the attachments which can be used to construct the Mail . Later , the SmtpClient class can be used to specify the host , port and the NetworkCredential to send the Mail that was composed earlier.

How to Send an Email via SMTP in C# ?

Below is a sample code snippet demonstrating how to send email via SMTP in C#.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Mail;
namespace GinktageConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string host, username, password, fromEmail, toEmail, Subject, Body;
            host = "<Your SMTP Host>";
            username = "<UserName>";
            fromEmail = "<From Email Address>";
            toEmail = "<To Email Address>";
            Subject = "This is a test Email";
            Body = "Test Message";
            password = "<Your Password>";
            int port = 25;
             using (MailMessage message = new MailMessage())
            {
                message.From = new MailAddress(fromEmail);
                message.To.Add(toEmail);
                message.Subject = Subject;
                message.Body = Body;              
                SmtpClient client = new SmtpClient(host, port);
                client.Credentials = new NetworkCredential(username, password);
                client.Send(message);
            }
            
            Console.ReadLine();
        }
       
    }
    
}

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply