require 'resolv' module MXRecord # Obtain the mail exchange record for a particular domain. # # Returns an array of Resolv::DNS::Resource::IN::MX records e.g. for Google: # # [ #, @ttl=347>, # #, @ttl=347>, # #, @ttl=347>, # #, @ttl=347>, # #, @ttl=347> ] def self.mail_servers(domain) Resolv::DNS.open do |dns| dns.getresources(domain, Resolv::DNS::Resource::IN::MX) end end # Obtain the preferred mail server based on the MX record's preference. # # Returns a String containing the mail server name e.g. aspmx.l.google.com; # returns nil if no servers are found. def self.primary_server(domain) servers = mail_servers(domain) return nil if servers.empty? primary_server = servers.first servers.each do |server| primary_server = server if server.preference < primary_server.preference end primary_server.exchange.to_s end end