Skip to content

Instantly share code, notes, and snippets.

@mrks111
Forked from peterc/email_list_mx_checker.rb
Created December 3, 2023 06:30
Show Gist options
  • Save mrks111/6739cc7b9fec32e26409afc53595fe3f to your computer and use it in GitHub Desktop.
Save mrks111/6739cc7b9fec32e26409afc53595fe3f to your computer and use it in GitHub Desktop.
Email list MX record checker
# Read stdin, extract email addresses
# Look up MX records for those addresses
# Return each email address and their first MX record
# (or IP address, as a fallback)
hosts = {}
STDIN.each_line do |l|
# Extract the email and the email domain from each line
email = l[/^([^\s]+\@[^\s+\,]+)\b/, 1]
host = email[/\@(.+)$/, 1]
# If already cached, use what was cached
if hosts[host]
dns = hosts[host]
else
# Do an MX lookup
mx = `dig MX +short #{host}`
dns = if mx =~ /[a-z]+/i
mx.downcase
else
# Technically mail can still work if the host
# has an A record
`dig A +short #{host}` =~ /[a-z]+/i ? a : 'FAIL'
end
# Just get the first entry
dns = dns.split("\n")[0]
hosts[host] = dns
end
puts "#{email},#{dns}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment