C# Program to send email through STMP (with Authentication) – asp.net

Step to program to send Email through C#:

1. Initialize the required inputs:

In our program, we have provided Name, Email, Phone number, Subject and Message as the string datatype and assigned values to those strings.

2. Create the Object for SmtpClient

SmtpClient mailSender = new SmtpClient();

Assign the values to the mailSender object. Some of the required fields are stmp url, port, username and password.

3. Create the object for MailMessage

MailMessage mailMsg = new MailMessage();

4. Send your email!

Now, you can send you email through mailSender.Send(mailMsg);

SmtpObject.Send(MailMessageObject);

Note: You need to import following Namespace.

1. using System.Net;
2. using System.Net.Mail;

 

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

namespace MailProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string name, email, mob, sub, msg;

            //inputs
            name = "aravind";
            email = "[email protected]";
            mob = "9710";
            sub = "sub";
            msg = "this is the data";

            //creating object for StmpClient
            SmtpClient mailSender = new SmtpClient("smtp.google.com", 587);
            mailSender.Credentials = new NetworkCredential("[email protected]", "somepass");       
            mailSender.EnableSsl = true;

            //creating object for MailMessage
            MailMessage mailMsg = new MailMessage("[email protected]", email, sub, msg);
            mailMsg.Priority = MailPriority.High;
            mailMsg.IsBodyHtml = true;
            mailMsg.SubjectEncoding = System.Text.Encoding.UTF8;

            //Sending Mail
            try
            {
                mailSender.Send(mailMsg);
                Console.WriteLine("Successfully Submitted!");

            }

            //catching the exception
            catch (Exception err)
            {
                Console.WriteLine(err.Message.ToString());
            }

        }
    }
}

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.