7

I have the following SMTP details stored in web.config

<system.net>
    <mailSettings>
      <smtp from="isds@ixtent.com">
        <network host="mail.domain.com" port="25" userName="username" password="password" defaultCredentials="true"/>
      </smtp>
    </mailSettings>
  </system.net>

How can I retrieve these values from within a c# class.

Çağdaş Tekin
  • 16,592
  • 4
  • 49
  • 58
JL.
  • 78,954
  • 126
  • 311
  • 459

3 Answers3

18
Configuration configurationFile = WebConfigurationManager
    .OpenWebConfiguration("~/web.config");
MailSettingsSectionGroup mailSettings = configurationFile
    .GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
    int port = mailSettings.Smtp.Network.Port;
    string host = mailSettings.Smtp.Network.Host;
    string password = mailSettings.Smtp.Network.Password;
    string username = mailSettings.Smtp.Network.UserName;
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

If you need to send email with this mail-server-details you don't need to read the settings and apply. These settings are applied implicitly in the application.

If you are reading it for any other reason I was about to write something similar to Darin's answer. But just as I was writing I found he answered so please refer to his answer if you actually need to read. :)

this. __curious_geek
  • 42,787
  • 22
  • 113
  • 137
0

What about:

string fullpath = @"C:\FullPath\YourFile.config";
string configSection = "system.net/mailSettings";
Configuration config = ConfigurationManager.OpenExeConfiguration(fullpath);
MailSettingsSectionGroup settings = 
    config.GetSectionGroup(configSection) as MailSettingsSectionGroup; 
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162