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();
        }
       
    }
    
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...