DEV Community

Olen Daelhousen
Olen Daelhousen

Posted on

2 2

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
}

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️