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?
+1
A:
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
David Stratton
2009-09-19 02:52:31
Thanks for the heads-up about My.Settings. I don't see that anywhere in the VB.NET book I have, which is probably just a port from the author's C# version of the book. Both are by Troelsen.
Slack
2009-09-19 04:14:36
+4
A:
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
bobbymcr
2009-09-19 02:57:07
Hmpfh. I hadn't tried this myself. I always did it using the method I suggested. I'll have to try this next time. +1 - Good answer.
David Stratton
2009-09-19 02:59:50
Thanks. The above works just fine for me. After much head scratching, I learned that there's a bug in Azure Worker Roles which cause app.config to be ignored. That was my problem. See http://blogs.msdn.com/jnak/archive/2009/08/17/using-app-config-in-the-july-2009-ctp.aspx
Slack
2009-09-19 04:33:41
A:
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.
feroze
2009-09-19 02:57:36
I think your XML didn't post. Angle brackets are probably stripped out by StackOverflow unless you take special measures.
Slack
2009-09-19 04:10:49