How can I read the email address, smtp host, port number from my mail settings section of the web.config file in an asp.net web application? Yeah, we can specify an email address in the mail settings section of web.config file and read it from asp.net web page in the time of sending an email. We can also read the smtp host and port number which is necessary while sending email from an asp.net web page. I have already discussed: How to send email from asp.net web page. So here I would just put the coding to read email address, host, port number from mail settings section of web.config file in asp.net web application.
Let's look into the mail setting portion of a web.config file.
<network host="mymailhostaddress" port="25"/>
While sending an email, we need from, to email addresses and an smtp client also. So the code snippet below puts them together.
//the method to send email
public void SendMail()
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
SmtpSection smtpSection = mailSettings.Smtp;
//read the from email of the web.config file
string fromEmail = smtpSection.From;
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;
//..other code follows from here
//that sends the email
//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress(fromEmail), new MailAddress("email@example.com"));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;
//create smtp client and send mail
SmtpClient client = new SmtpClient(host, port);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
catch (Exception ex)
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;
Using the code above, we easily accessed the important information from mail settings section of the web.config file. Please note again that I have just put the coding of reading information form web.config file. You can learn from here to Send Email in asp.net web page so that you can combine what this article provides with sending email in asp.net web application. Happy Programming!