Shell script to parse a list of emails and check if their mx record is on a file

Issue

I needed a shell script that parses a txt with emails and does a simple dig:
Grab the domain from the email:

echo [email protected] | awk -F "@" '{print $2}'

and the dig

dig @127.0.0.1 +short mx $domain | sed 's/\.$//'

on an email and i needed to check if any of the MX records are present in a file.
This file contains the big email service providers mx records for example:

aa-com.mail.protection.outlook.com
alt1.gmail-smtp-in.l.google.com

if any of those mx matches i want to put these emails on another file so that i have private domains on one side and ESP’s on the other file.

any help is appreciated.
thanks in advance

Solution

#/bin/bash
cat emails.txt |while read email
do 
    domain=$(echo $email | awk -F "@" '{print $2}')
    dig +short mx $domain |awk '{print $2}'|sed 's/\.$//' |while read mx
    do
        if grep -qs $mx mx_records.txt
        then
            echo $email
            break
        fi
    done
done

There is a number at the beginning of the dig output,

# dig mx apple.com  +short
10 rn-mailsvcp-ppex-lapp34.apple.com.
10 rn-mailsvcp-ppex-lapp45.apple.com.
10 rn-mailsvcp-ppex-lapp44.apple.com.

so i filtered them with awk '{print $2}'.

This script prints the matched emails as a standerd output, you can redirect the output to another file.

Answered By – zzwei

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published