Search code examples
.netwebformsasp-classic

How do I get mailsettings form webconfig file on a classic asp page


Currently working on a classic asp page and wanted to find out how would one go about sending an email when an event occurs on the page. using server-side coding, ie no javascript; how would I read the mailsetting within the web.config file on a classic asp page.


Solution

  • You can use the MSXML2.DOMDocument.6.0 object to load and read the web.config file and extract elements.

    Example web.config:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.net>
        <mailSettings>
          <smtp deliveryMethod="Network" from="smtp@example.com">
            <network 
                defaultCredentials="true" 
                host="localhost" 
                port="587" 
                userName="username" 
                password="password"/>
          </smtp>
        </mailSettings>
      </system.net>
    </configuration>
    

    Read using MSXML2.DOMDocument.6.0:

    <%
    
        Dim oXML, oNode
        
        Set oXML = Server.CreateObject("MSXML2.DOMDocument.6.0")
        
            oXML.async = False    
            oXML.load Server.MapPath("/web.config")
            
            ' smtp attributes
            
            Set oNode = oXML.selectSingleNode("configuration/system.net/mailSettings/smtp")
                    
                Response.Write "<b>deliveryMethod:</b> " & oNode.GetAttribute("deliveryMethod") & "<br>"
                Response.Write "<b>from:</b> " & oNode.GetAttribute("from") & "<br>"
            
            ' network attributes
                                                
            Set oNode = oXML.selectSingleNode("configuration/system.net/mailSettings/smtp/network")
                    
                Response.Write "<b>defaultCredentials:</b> " & cBool(oNode.GetAttribute("defaultCredentials")) & "<br>"
                Response.Write "<b>host:</b> " & oNode.GetAttribute("host") & "<br>"
                Response.Write "<b>port:</b> " & cInt(oNode.GetAttribute("port")) & "<br>"
                Response.Write "<b>userName:</b> " & oNode.GetAttribute("userName") & "<br>"
                Response.Write "<b>password:</b> " & oNode.GetAttribute("password")
                                        
            Set oNode = Nothing
            
        Set oXML = Nothing
        
    %>
    

    Output:

    deliveryMethod: Network
    from: smtp@example.com
    defaultCredentials: True
    host: localhost
    port: 587
    userName: username
    password: password