royco
royco

Reputation: 5529

Getting System.Net.Mail to read from app.settings?

In ASP.NET, I can just put my mailSettings in web.config and then System.Net.Mail.SmtpClient's default constructor will read them. In a regular VB.NET project, not ASP.NET, I thought I could just put mailSettings in app.config. However, SmtpClient() doesn't appear to read settings from app.config. Is there a step I'm missing in order to tell a VB.NET application to read from app.config?

Upvotes: 1

Views: 2660

Answers (3)

David
David

Reputation: 73574

the Asp.Net runtime has extra code to handle this for you, probably because the designers expect sending emails to be a normal part of a web site's operations (but I probably shouldn't guess about Microsoft's motives.)

You can read the setting yourself and set the smtp host by reading the settings with the System.Configuration.ConfigurationManager.

Or, since you're in VB, you can access this more easily by using My.Settings

Upvotes: 1

feroze
feroze

Reputation: 7594

The SmtpClient will not read it automagically, but you can do it easily...

for eg, in V2.0 of the framework, you could do this:

String host = (String)ConfigurationSettings.AppSettings["SmtpHostName"]

and in your app.exe.config file:

<configuration>
<appSettings>
<add key="SmtpHostName" value="Smtp.mydomain.com"/>
</appSettings>
</configuration>

Hope this helps.

Upvotes: 0

bobbymcr
bobbymcr

Reputation: 24167

This appears to work for me:

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <mailSettings>
      <smtp>
        <network host="mysmtphost" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

Module1.vb

Imports System.Net.Mail

Module Module1

    Sub Main()
        Dim client As New SmtpClient()
        Console.WriteLine(client.Host)
        ' output is "mysmtphost" as expected
    End Sub

End Module

Upvotes: 5

Related Questions