HomeCSharpHow to Send an Email via SMTP in C# ?

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...