Uncategorized

Accessing SMTP Mail Settings defined in Web.Config File Programmatically

I needed to read my SMTP email settings defined under system.net section in my web.config file. In order to use eNewsLetter and other SiteAdmin CMS modules that sending email notifications; you can setup your web.config to defind SMTP services settings.

Below is one example of SMTP email setting defined in web.config file:
(Under <configuration> Section)

    <system.net>
        <mailSettings>
            <smtp deliveryMethod=”Network” from=”testuser@domail.com”>
                <network defaultCredentials=”true” host=”localhost” port=”25″ userName=”kaushal” password=”testPassword”/>
            </smtp>
        </mailSettings>
    </system.net>

To Access, this SMTP Mail Setting Programatically, you need to import below namespaces:

using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;

The .NET Framework provides APIs for accessing settings in a configuration file. Below is how you access the SMTP mail settings of a web.config file in code:

        Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
        MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup(“system.net/mailSettings”);
        Response.Write(“host: ” + settings.Smtp.Network.Host + “<br />”);
        Response.Write(“port: ” + settings.Smtp.Network.Port + “<br />”);
        Response.Write(“Username: ” + settings.Smtp.Network.UserName + “<br />”);
        Response.Write(“Password: ” + settings.Smtp.Network.Password + “<br />”);
        Response.Write(“from: ” + settings.Smtp.From + “<br />”);

Thats it!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.