Finding the MX Record using C#?

Doron Sinai picture Doron Sinai · Nov 26, 2010 · Viewed 10.8k times · Source

How can I find the MX record for a mail server in C#?

Answer

user333306 picture user333306 · Nov 26, 2010

You can use the answer of Robert and RPK to get the MX record of a given domain.

But you'll need a DNS server to do the job. If you want to detect the DNS server of the machine where your code is executed, you can use the following.

NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
    IPInterfaceProperties properties = adapter.GetIPProperties();

    if (properties.DnsAddresses.Count > 0)
        foreach (IPAddress ipAddress in properties.DnsAddresses)
             dnsServers.Add(ipAddress.ToString(), 53);
}

There is a complete solution (or at github here) that will do the whole job if you don't want to rewrite everything. Look for GetMxRecords static method.