Sample code for 30+ languages & platforms
SQL Server

MX Lookup Mail Server Domain by Email Address

How to find the mail server for a given email address. Returns the domain name of the primary mail server.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    -- This example requires the Chilkat API to have been previously unlocked.
    -- See Global Unlock Sample for sample code.

    DECLARE @dns int
    EXEC @hr = sp_OACreate 'Chilkat.Dns', @dns OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    DECLARE @json int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @json OUT

    DECLARE @emailAddr nvarchar(4000)
    SELECT @emailAddr = 'bob@example.com'

    -- This gets all MX domains for an email address.  (Typically one domain.)
    -- The preferred domain will be at index 0 (see below).
    EXEC sp_OAMethod @dns, 'Query', @success OUT, 'MX', @emailAddr, @json
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @dns, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @dns
        EXEC @hr = sp_OADestroy @json
        RETURN
      END

    DECLARE @i int
    SELECT @i = 0
    DECLARE @count_i int
    EXEC sp_OAMethod @json, 'SizeOfArray', @count_i OUT, 'answer.mx'
    WHILE @i < @count_i
      BEGIN
        EXEC sp_OASetProperty @json, 'I', @i
        DECLARE @domain nvarchar(4000)
        EXEC sp_OAMethod @json, 'StringOf', @domain OUT, 'answer.mx[i].domain'

        PRINT @domain
        SELECT @i = @i + 1
      END

    EXEC @hr = sp_OADestroy @dns
    EXEC @hr = sp_OADestroy @json


END
GO