Monitor Mail DNS & Check Enrollment Email in Node.js
This guide shows you how to build a Node.js script that monitors your mail-related DNS records (MX, SPF, DKIM, DMARC) and checks whether an enrollment email has been delivered to a mailbox. You’ll get a practical, repeatable process using widely-used libraries, with clear steps for setup, execution, and troubleshooting.
What You’ll Need
- Node.js installed (version 14 or later recommended).
- Access to a terminal or command prompt.
- A domain name whose DNS records you want to check.
- An email account (or a test mailbox) that can receive the enrollment email.
- Basic familiarity with JavaScript and asynchronous programming.
Step-by-Step
- Set up a new Node.js project. Create a directory, navigate into it, and run
npm init -yto generate apackage.jsonfile. - Install required packages. Run
npm install dns-query imapflow. Thedns-querypackage lets you query DNS records directly, andimapflowis a modern IMAP client for checking email. - Create a script file. Name it
monitor.jsand open it in your editor. - Import the modules. At the top of the file, add:
const { query } = require('dns-query'); const { ImapFlow } = require('imapflow'); - Define the DNS records to monitor. For each record type (MX, TXT for SPF, DKIM, DMARC), you’ll query the domain. For example, to get MX records:
async function getMX(domain) { const result = await query({ qname: domain, qtype: 'MX' }); return result.answers; } - Add functions for SPF, DKIM, and DMARC. SPF is a TXT record on the root domain. DKIM is a TXT record on a selector (e.g.,
default._domainkey.yourdomain.com). DMARC is a TXT record on_dmarc.yourdomain.com. Write separate functions that query each and return the answers. - Create a function to check all DNS records. Combine the above into a single
checkDNS(domain)function that calls all four queries and logs the results. Wrap each query in a try/catch to handle failures gracefully. - Set up IMAP connection. Use
ImapFlowto connect to your mailbox. You’ll need the host, port, user, and password. Example:const client = new ImapFlow({ host: 'imap.example.com', port: 993, secure: true, auth: { user: 'you@example.com', pass: 'password' } }); - Write a function to check for the enrollment email. Connect to the mailbox, search for emails from a specific sender or with a subject line containing “enrollment”, and return the latest matching message. Use
client.search()to find messages, thenclient.fetchOne()to get details. - Combine everything in a main function. Call
checkDNS(domain)and the email check function. Log the DNS records and whether the email was found. If the email isn’t found, log a warning. - Run the script. Execute
node monitor.jsin the terminal. You should see the DNS records printed and the email status.
Common Mistakes
- Incorrect DKIM selector: The selector is not always
default. Check your email provider’s documentation for the correct selector. - Using the wrong DNS query type: SPF and DMARC are TXT records, not separate types. Make sure you query TXT.
- Not handling DNS timeouts: DNS queries can hang. Set a timeout in your query options (e.g.,
timeout: 5000). - IMAP credentials wrong or insecure: Double-check the host, port, and that you’re using SSL. Never hardcode passwords in production; use environment variables.
- Search criteria too narrow: If the email subject has extra spaces or punctuation, your search may fail. Use a broader search and then filter.
Tips
- Use environment variables for sensitive data like email passwords. Use
process.env.IMAP_PASSinstead of hardcoding. - Add logging with timestamps to track when checks run, especially if you schedule the script.
- Schedule the script with cron or a task scheduler to run periodically (e.g., every 5 minutes) for continuous monitoring.
- Validate DNS records against known good values. For example, SPF should include the email provider’s designated servers.
- Test with a real email before relying on the script. Send a test enrollment email to ensure your search criteria work.
Troubleshooting
- DNS query returns empty or error: Check your network connection, domain spelling, and that the record actually exists. Use tools like
digto verify manually. - IMAP connection fails: Verify the host and port. For Gmail, you may need an app-specific password if 2FA is enabled. For Outlook, use the correct server (e.g., outlook.office365.com).
- Email not found even though it exists: Check the search criteria. Try searching by sender email only, or use
seen:falseto find unread emails. - Script hangs: Add timeouts to both DNS queries and IMAP operations. For IMAP, set
connectionTimeoutandgreetingTimeoutin the client options. - Rate limiting: If you query DNS too frequently, you may be temporarily blocked. Add delays between checks if needed.
Frequently Asked Questions
Can I use this script with any email provider?
Yes, as long as your provider supports IMAP. You’ll need the correct IMAP server and port, which you can usually find in your provider’s help pages.
How do I find the DKIM selector for my domain?
Check your email service provider’s documentation. Often it’s something like default, google, or selector1. You can also look at the headers of a received email from that domain to see the selector.
What if I don’t want to store my email password in the script?
Use environment variables or a configuration file that is not committed to version control. For example, set process.env.IMAP_PASS in your shell before running the script.
Can I monitor multiple domains?
Yes, wrap the DNS check in a loop over an array of domains. For email checking, you’ll need separate IMAP connections for each mailbox.
How often should I run this script?
It depends on your needs. For critical enrollment emails, you might check every minute. For general DNS health, every hour is fine. Be mindful of rate limits.
Why is my SPF record not showing up?
SPF is stored as a TXT record. Make sure you’re querying TXT, not SPF (which is obsolete). Also, some DNS providers may have propagation delays.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.