Node.js: check if users have Gmail on their domains

In Node.js is quite simple to check whether users use Gmail on their domains.

Given an e-mail address, we first get the relevant MX records by performing a DNS query on the domain. Then we check whether the returned MX values contain one of the main substrings used by Gmail (either for simple and business accounts).


'use strict';

const getMXRecords = email => {
    const dns = require('dns');
    return new Promise((resolve, reject) => {
        let domain = email.split('@')[1];
        dns.resolve(domain, 'MX', (err, addresses) => {
            if(err) {
                reject(err);
            } else {
                resolve(addresses);
            }
        });
    });
};

const isGmailUser = async email => {
      try {
          let records = await getMXRecords(email);
          let found = false;

          if(Array.isArray(records) && records.length > 0) {
              records.forEach(record => {
                 if(record.exchange && typeof record.exchange === 'string') {
                     if(record.exchange.includes('google.com') || record.exchange.includes('googlemail.com')) {
                         found = true;
                     }
                 }
              });
          }
          return found;
      } catch(err) {
          return false;
      }
};

Finally, we test the results.


'use strict';

const test = async email => {
    try {
       let result = await isGmailUser(email);
       console.log( email + ': ' + result );
    }  catch(err) {
        console.log(err);
    }
};

test('gabriele.romanato@gmail.com'); // true
test('gabriele@gabrieleromanato.com'); // true
test('gabriele@gabrieleromanato.name'); // false

Articles