Search code examples
c#.netemailapp-config

SmtpClient and app.config system.net configuration


I'm having an issue with a .NET 3.5 library I'm developing to send emails. I put the system.net configuration into app.config:

<system.net>
  <mailSettings>
    <smtp from="[email protected]">
      <network host="myserver.com" port="25" defaultCredentials="true" />
    </smtp>
  </mailSettings>
</system.net>

And I instantiate the SmtpClient without params:

SmtpClient client = new SmtpClient();

But the configuration is not read (I'm trying to test the library with NUnit) and I get a System.InvalidOperationException, because the configuration is not read and thus the host is null.

Shouldn't the configuration be read automatically?


Solution

  • Make sure you add your configuration block (as shown above) to the {appName}.exe.config or web.config - the configuration for the class library is taken from one of those files at runtime, not from the app.config of the class library.