views:

317

answers:

1

Hello we have a Business Logic Layer which has an Email Services Class. In this class we have a method which will create an email(This part works and compiles fine). However when we try to access the app config file in order to test the method we get an error saying - Can't retrieve the app config mail settings and says all values are null when they are not. Here is the app config section for our code:


<mailSettings>
  <smtp deliveryMethod="Network" from="[email protected]">
    <network host="localhost" port="25" defaultCredentials="true"/>
  </smtp>
</mailSettings>

Here is there code we use to connect to the app.config:


private System.Net.Configuration.MailSettingsSectionGroup mailSettings;

SmtpClient client = new SmtpClient(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port);


What are we doing wrong here?

+2  A: 

Your mailSettings variable isn't initialised to anything - it won't magically contain your configuration.

You need to use the ConfigurationManager class to access it (remember to add a reference to System.Configuration if not already done so.) You will also need to add using System.Net.Configuration for the following code.

SmtpSection smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;

if (smtpSection != null)
{
    SmtpClient client = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
}
Andy Shellam
It still doesn't seem to find it using this code.
mw
It worked for me in a test app. Does smtpSection come out as null?
Andy Shellam