Over a million developers have joined DZone.

Find Primary MX Record

DZone's Guide to

Find Primary MX Record

· ·
Free Resource
// description of your code here

# Returns the highest priority MX record server for a domain or nil.
#   get_MX_server('mydomain.com') # => 'smtp.mydomain.com'
def get_MX_server(domain)
  require 'resolv'
  mx = nil
  Resolv::DNS.open do |dns|
    mail_servers = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
    return nil unless mail_servers and not mail_servers.empty?
    highest_priority = mail_servers.first
    mail_servers.each do |server|
      highest_priority = server if server.preference < highest_priority.preference
    mx = highest_priority.exchange.to_s
  return mx

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}