Skip to content

Instantly share code, notes, and snippets.

@r0yfire
Last active December 14, 2021 16:00
Show Gist options
  • Save r0yfire/c565213598f32b02f13153f8096d2717 to your computer and use it in GitHub Desktop.
Save r0yfire/c565213598f32b02f13153f8096d2717 to your computer and use it in GitHub Desktop.
Validate email domains of prospects to ensure they are deliverable using Autohost API
const csv = require('@fast-csv/parse');
const https = require('https');
// Autohost API client
const client = (path, data, method = 'GET') => {
return new Promise((resolve, reject) => {
const options = {
method,
hostname: 'data.autohost.ai',
port: 443,
protocol: 'https:',
path,
headers: {
'x-api-key': 'ENTER-YOUR-API-KEY',
}
};
const req = https.request(options, res => {
const chunks = [];
res.setEncoding('utf8');
res.on('data', chunk => chunks.push(chunk));
res.on('end', () => {
let body = chunks.join('');
const status = res.statusCode;
if (status >= 400) {
return reject(body);
}
try {
body = JSON.parse(body);
} catch (error) {
// console.log(error);
}
return resolve(body);
});
});
req.on('error', error => reject(error));
if (data) {
try {
data = JSON.stringify(data);
req.setHeader('Content-Type', 'application/json');
req.write(data);
} catch (e) {
console.error(e);
}
}
req.end();
});
};
// validate email address on Autohost
const emailValidation = async (email) => {
let res;
try {
res = await client(`/v1/validate/email/${encodeURIComponent(email)}`);
}
catch (error) {
console.log(error);
}
return res;
};
// load emails from CSV file and return list of unique domains
const parseCSV = () => new Promise((resolve, reject) => {
const domains = {};
csv.parseFile('./leads.csv', { headers: true })
.on('error', error => console.error(error))
.on('data', async (row) => {
const email = row.email;
const domain = email.split('@')[1].trim();
domains[domain] = domains[domain] ? domains[domain] + 1 : 1;
})
.on('end', () => resolve(Object.keys(domains)));
});
// main handler
const main = () => {
const invalid = [];
(async () => {
const domains = await parseCSV();
console.log(`Total unique domains: ${domains.length}`);
for (let i = 0; i < domains.length; i++) {
const domain = domains[i];
const res = await emailValidation(`test@${domain}`);
if (res) {
if (res.status === 'INVALID') {
console.log(`[!] ${domain} is invalid :(`);
invalid.push(domain);
}
if (res.status === 'VALID') {
console.log(`${domain} is valid`);
}
}
}
// This will cause API throttling
// const promises = domains.map(async (domain) => {
// const res = await emailValidation(`test@${domain}`);
// if (res && res.status !== 'VALID') {
// invalid.push(domain);
// }
// });
// await Promise.all(promises);
console.log(JSON.stringify(invalid, null, 2));
})();
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment