Accessing Config File Mail Settings Programmatically
Some people may not know that .NET 2.0 provides APIs for accessing everything in a configuration file. The most common question I see relates to accessing the mail settings in the system.net node programmatically.
C#
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("PathToConfigFile");
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;
}
VB.NET
Imports System.Configuration
Imports System.Web.Configuration
Imports System.Net.Configuration
Dim configurationFile As Configuration = WebConfigurationManager.OpenWebConfiguration("PathToConfigFile")
Dim mailSettings As MailSettingsSectionGroup = configurationFile.GetSectionGroup("system.net/mailSettings")
If Not mailSettings Is Nothing Then
Dim port As Integer = mailSettings.Smtp.Network.Port
Dim host As String = mailSettings.Smtp.Network.Host
Dim password As String = mailSettings.Smtp.Network.Password
Dim username As String = mailSettings.Smtp.Network.UserName
End If
Similar Posts
- Sending an email using System.Net.Mail
- Reading an XML file
- Getting the content of a GridView cell on edit





Comments
Larry on on 4.09.2006 at 5:36 PM
Question: Is there a way to force it to load mail settings from web.config without having to specify the exact path?
Ryan Olshan on on 4.09.2006 at 9:50 PM
Hi Larry,
If you specify the SMTP server settings in Web.config, ASP.NET will automatically use them when you send an email.