Weak Validate an Email Address Using Node to Check if an MX Record Exists

olen_d

Olen Daelhousen

Posted on February 17, 2020

Weak Validate an Email Address Using Node to Check if an MX Record Exists

For the web application I'm working on, having a valid email address for each user is important because the application allows users to contact each other, but retain some privacy, by using double-blind emails. To ensure the user has submitted a working email address, the application sends a verification code to the address entered at sign-up. However, to avoid unnecessary bounces I wanted a way to filter out obviously fake addresses that still passed validation using regular expressions.

I learned that Node includes a DNS module that can be used to look up a host and return an MX record, if it exists. Therefore, if the DNS module fails to return an MX record, the email address entered by the user is not valid.

The code below uses the dnsPromises API to check if an MX record exists for an arbitrary email address. To use, just pass the mxExists function an email address and it will return a promise. If the domain doesn't exist or no MX record is found, the promise will reject or resolve as false. If an MX record is found, the promise will resolve as true. Individual mailboxes are not validated, so bounces are still possible. The intent of the weak validation is to catch typos and obvious fake addresses to reduce the bounce rate.

const dnsPromises = require("dns").promises;

const mxExists = email => {
  return new Promise ((res, rej) => {
    const hostname = email.split("@")[1];

    try {
      dnsPromises.resolveMx(hostname).then(addresses => {
        if (addresses && addresses.length > 0) {
          addresses[0].exchange ? res(true) : res(false);
        }
      })
      .catch(err => {
        // TODO: Deal with the error
        console.log("mx-check.js - resolveMx ERROR:\n" + err);
        res(false);        
      });
    } catch (err) {
      // TODO: Deal with the error
      console.log("mx-check.js ERROR:\n" + err);
      rej(false);
    }
  });
}

module.exports = {
  mxExists
}
💖 💪 🙅 🚩
olen_d
Olen Daelhousen

Posted on February 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related