Here I will Show you How to send an email with app setting in web Config file ,Later on I will explain the advantages why I have setting the main setting in the web configuration file. So let’s starts with email sending code in Asp.net. This is the code of email send with mail setting in web configuration file
On the aspx.cs page
Mail Message message = new MailMessage ();
MailAddress Sender = new MailAddress (ConfigurationManager.AppSettings ["smtpUser"]);
MailAddress receiver = new MailAddress (txtemail.Text);
SmtpClient smtp = new SmtpClient()
{
Host = ConfigurationManager.AppSettings ["smtpServer"],
Port = Convert.ToInt32 (ConfigurationManager.AppSettings ["smtpPort"]),
EnableSsl = true,
Credentials = new System.Net.NetworkCredential (ConfigurationManager.AppSettings ["smtpUser"], ConfigurationManager.AppSettings ["smtpPass"])
};
message.From = Sender;
message.To.Add(receiver);
message.Body = txtbody.Text;
message.IsBodyHtml = true;
smtp.Send(message);
Here is the design for this we have to write it on on .aspx page
Email ID <asp:TextBox ID="txtemail" runat="server"></asp:TextBox><br />
Subject <asp:TextBox ID="txtsubject" runat="server"></asp:TextBox><br />
Body <asp:TextBox ID="txtbody" runat="server" TextMode="MultiLine"></asp:TextBox><br />
<asp:Button ID="btnSendmail" runat="server" Text="Send"
onclick="btnSendmail_Click"/>
2nd Now I will show you the simple email sending code with no code setting in web Config File
Mail Message message = new MailMessage ();
MailAddress Sender = new MailAddress ( sender@mail.com);
MailAddress receiver = new MailAddress (reciver@mail.com@mail.com);
SmtpClient smtp = new SmtpClient()
{
Host = "smtp.gmail.com", Port = 587 Credentials = new System.Net.NetworkCredential (youremailaddress,Your Password)
};
message.From = Sender;
message.To.Add(receiver);
message.Body = txtbody.Text;
message.IsBodyHtml = true;
smtp.Send(message);
Email setting in web Configuration file
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="smtpServer" value="smtp.gmail.com" />
<add key="EnableSsl" value = "true"/>
<add key="smtpPort" value="587" />
<add key="smtpUser" value="abhimanyu.vij@gmail.com" />
<add key="smtpPass" value="*****" />
</appSettings>
Advantages for setting the email setting in the web configuration file
The main advantages of set the email setting in web configuration file is code reusability because once we write the code on aspx.cs page we no need to change the setting on the page we simply change the setting in the web config file ,suppose if we write the code on aspx.cs page like I did in the 2nd case and if if want to use the code for any other project then we need to change the setting on the aspx.cs page which is very cumbersome so always set the email setting on the web configuration page that’s all