Skip to content

Instantly share code, notes, and snippets.

@smddzcy
Created March 23, 2020 20:21
Show Gist options
  • Save smddzcy/10c66f43e3a5d0046cb2dffb0bdffd38 to your computer and use it in GitHub Desktop.
Save smddzcy/10c66f43e3a5d0046cb2dffb0bdffd38 to your computer and use it in GitHub Desktop.
Validate bulk mail list using NPM package `email-deep-validator`.
const EmailValidator = require('email-deep-validator');
const path = require('path');
const fs = require('fs');
const throat = require('throat');
const emailValidator = new EmailValidator();
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const retry = async (fn, retryCount = 2, intervalMs = 500, originalError = null) => {
if (retryCount === 0) {
if (!originalError) throw new Error('Failed after 3 retries');
throw originalError;
}
try {
const res = fn();
if (res && typeof res.catch === 'function') {
return res.catch(err => wait(intervalMs).then(() => retry(fn, retryCount - 1, intervalMs, err)));
}
return res;
} catch (err) {
await wait(intervalMs);
return retry(fn, retryCount - 1, intervalMs, err);
}
};
const validate = async address => {
try {
const { wellFormed, validDomain, validMailbox } = await retry(() => emailValidator.verify(address));
return wellFormed !== false && validDomain !== false && validMailbox !== false;
} catch (err) {
return true;
}
}
const main = async (fileIn, fileOut) => {
if (!fileIn) {
console.error('Filename is empty, e.g. `node mail-validate.js emails.txt`')
process.exit(1);
return;
}
console.log(`Validation started...`);
const items = fs.readFileSync(path.join(__dirname, fileIn)).toString().split('\n').map(e => e.trim());
const emailRegex = /.*<(.*?)>/;
const filteredItems = (await Promise.all(items.map(throat(50, async item => {
const email = item.includes('<') ? item.match(emailRegex)[1] : item;
const isCorrect = await validate(email);
console.log(`${email}: ${isCorrect ? '✅' : '⛔️'}`);
return isCorrect ? item : null;
})))).filter(e => !!e);
console.log(`Done: ${filteredItems.length} out of ${items.length} are valid`);
fs.writeFileSync(path.join(__dirname, fileOut), filteredItems.join('\n'));
process.exit(0);
}
main(process.argv[2], process.argv[3] || 'out.txt');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment