Skip to content

Instantly share code, notes, and snippets.

@felippe-regazio
Created May 17, 2021 14:14
Show Gist options
  • Save felippe-regazio/b724ebdc9097ec6209c7914adedc18e5 to your computer and use it in GitHub Desktop.
Save felippe-regazio/b724ebdc9097ec6209c7914adedc18e5 to your computer and use it in GitHub Desktop.
Check DNS MX entries to validate if the domain part of a given email is valid.
const dns = require('dns');
/**
* Mail Exchange (MX) records are DNS records that are necessary for delivering email to your address.
* In simple DNS terms, an MX record is used to tell the world which mail servers accept incoming mail
* for a given domain. So we can use the domain part of any email to check MX records, if there is
* records it means its a valid email service, otherwise is not.
*
* WARNING: By checking the MX Records you dont check if the email is valid or if exists, you check
* if the EMAIL SERVICE is valid and exists. Anyway is a good filter for spammers and avoid waste
* resources with obviously invalid emails.
*
* This functions accepts and email and returns a Promise with the MX records, meaning its a valid
* email service, or an error, meaning that the MX doenst exists or the checking has failed.
*
* @param {String} email
* @returns {Promise}
*/
function checkMX(email) {
const domain = email.split('@')[1];
return new Promise((resolve, reject) => {
dns.resolve(domain, 'MX', (err, mxAddrs) => {
err && reject(err);
mxAddrs && mxAddrs.length ?
resolve(mxAddrs) :
reject(new Error(`No MX entries found for "${domain}"`));
});
});
}
/**
* Usage:
*
* For a valid email, will return something like:
*
* [ { exchange: 'alt1.gmail-smtp-in.l.google.com', priority: 10 },
* { exchange: 'alt2.gmail-smtp-in.l.google.com', priority: 20 },
* { exchange: 'alt4.gmail-smtp-in.l.google.com', priority: 40 },
* { exchange: 'gmail-smtp-in.l.google.com', priority: 5 },
* { exchange: 'alt3.gmail-smtp-in.l.google.com', priority: 30 } ]
*/
checkMX('[email protected]')
.then(console.log)
.catch(console.error);
/**
* Usage:
*
* For and invalid email, will return something like
*
* { Error: queryMx ENOTFOUND whatever123a.com
* at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
* errno: 'ENOTFOUND',
* code: 'ENOTFOUND',
* syscall: 'queryMx',
* hostname: 'whatever123a.com' }
*/
checkMX('[email protected]')
.then(console.log)
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment