Created
March 13, 2023 12:53
-
-
Save peterc/668ddae7cff9531bfd01d4fc61f25187 to your computer and use it in GitHub Desktop.
Email list MX record checker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
I only built this for my own use and rate limiting on DNS could be an issue depending on your setup. However, the memoization helps a lot, and you can add @ entries to the dig calls if you need to route the DNS elsewhere. Google's 8.8.8.8 is usually good for hundreds of QPS.