Skip to content
June 5, 2009 / kiranpatils

How to Access MailSettings Configuration Settings Programmatically

Challenge:

I have my mail settings in web.config file in mailSettings section..like as shown below:

<system.net>
 <mailSettings>
 <smtp from=myEmail@mySite.com>
 <network defaultCredentials="true" host="mail.myhost.com" password="xxx" userName="xxx"/>
 </smtp>
 </mailSettings>
</system.net>

i like to access it in my code. How can i do that?

Solution:

In .NET World nothing is impossible[As per my thinking in real world too :)].

 //get current application's configuration file
 Configuration configurationFile =     WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); 
//access mailsetting section and cast it to MailSettingsSectionGroup Class
MailSettingsSectionGroup     
mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

 if (mailSettings != null)
 {
 string form = mailSettings.Smtp.From;
 int port = mailSettings.Smtp.Network.Port;
 string host = mailSettings.Smtp.Network.Host;
 string password = mailSettings.Smtp.Network.Password;
 string username = mailSettings.Smtp.Network.UserName;
 }

Hope this helps

Happy programming!!

2 Comments

Leave a Comment
  1. hcg diet kits / Feb 8 2013 8:09 am

    What’s Happening i’m new to this, I stumbled upon this I’ve discovered It absolutely useful and it has helped me out loads. I am hoping to contribute & help different customers like its aided me. Good job.

    • kiranpatils / Mar 23 2013 7:06 pm

      Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: