Sending email in c# using web config setting

How to send email from C#

Simple Mail Transfer Protocol (SMTP): Simple Mail Transfer Protocol (SMTP) is used for transferring mail from one device to another device it is comes under Application layer Protocol. it uses TCP Port 25 for communicating.
In this post i will tell  you how can you configure the SMTP email setting in ASP C# using web config setting on the button click Event. as Gmail is using widely so here i will follow the Gmail setting.

Step 1: First do Some Setting in Web Config file Which is given below.

<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="Your username" password="Your Password"/>
</smtp>
</mailSettings>
</system.net>

Put these setting in web config file inside the configuration tag.

Step 2: Create a Button and on the click event of button you can write the below code

protected void Button1_Click(object sender, EventArgs e)  //****On the Button Click Event
{
MailMessage mail = new MailMessage(); // creating Instance of mail-message
mail.Subject = "Your Subject"; // Your mail Subject
mail.From = new MailAddress("From Mail Address"); // From Address
mail.To.Add("To Mail Address"); // To Address
mail.Body = "Hii RochakTeam! your mail content goes here..."; //Your Mail Body
mail.IsBodyHtml = true;
// Here we will not specify the Smtp Setting because we already have done in Web Config File.
SmtpClient smtp = new SmtpClient();
try
{
smtp.Send(mail); // Sending Mail
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Success!! Mail Has Been Sent ');", true);//Show alert Message
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
}
}

That’s It Thanks for reading and please comment if it is works for you …………

Read More Tutorials:

Related posts

One Thought to “Sending email in c# using web config setting

Leave a Comment