How to search for SMTP Servers in a domain programmatically using ADSI?

Here is a sample vbscript using which we can get SMTP servers instance names in a particular domain pragmatically via ADSI.

NOTE: Following programming examples is for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This sample code assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. This sample code is provided for the purpose of illustration only and is not intended to be used in a production environment.

 Option Explicit
 Dim conn
 Dim com
 Dim iAdRootDSE
 Dim strNC
 Dim strQry
 Dim RS
 Dim strstmsrv
 Dim svsSmtpserver
 Dim crServerName
  
 set conn = createobject("ADODB.Connection")
 set com = createobject("ADODB.Command")
 Set iAdRootDSE = GetObject("LDAP://RootDSE")
  
 strNC = iAdRootDSE.Get("configurationNamingContext")
  
 conn.Provider = "ADsDSOObject"
 conn.Open "ADs Provider"
 com.ActiveConnection = Conn
 com.ActiveConnection = Conn
  
 Wscript.echo
 Wscript.echo "SMTP Virtual Servers"
  
 'Get SMTP server query using protocolCfgSMTPServer object class
 strQry = "<LDAP://" & strNC & ">;(objectCategory=protocolCfgSMTPServer);name,distinguishedName;subtree"
  
 com.ActiveConnection = conn
 com.CommandText = strQry
  
 Set RS = com.Execute
  
 While Not RS.EOF
     strstmsrv = "LDAP://" & rs.fields("distinguishedName")
     set svsSmtpserver = getobject(strstmsrv)
     crServerName = mid(svsSmtpserver.distinguishedName,instr(svsSmtpserver.distinguishedName,"CN=Protocols,")+16,instr(svsSmtpserver.distinguishedName,",CN=Servers")-(instr(svsSmtpserver.distinguishedName,"CN=Protocols,")+16))
     wscript.echo
     wscript.echo "ServerName:" & crServerName
     
     RS.movenext
 wend
  
 Set RS=Nothing
 Set com=Nothing
 Set conn=Nothing

 

Here is another good example of where protocolCfgSMTPServer object class is used to find SMTP Virtual Server and set Message Restriction on an SMTP Virtual Server Using ADSI in VB @ Setting Message Restriction on an SMTP Virtual Server Using ADSI.

Hope this helps.