smartmail/ts/smartmail.classes.emailaddressvalidator.ts

59 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-06-18 15:34:05 +00:00
import * as plugins from './smartmail.plugins';
2020-06-18 21:04:52 +00:00
import * as paths from './smartmail.paths';
2020-06-18 15:34:05 +00:00
export interface IEmailValidationResult {
valid: boolean;
2020-06-18 21:04:52 +00:00
disposable: boolean;
freemail: boolean;
2020-06-18 15:34:05 +00:00
reason: string;
}
export class EmailAddressValidator {
2020-06-18 21:04:52 +00:00
public domainMap: { [key: string]: 'disposable' | 'freemail'};
2020-06-18 15:34:05 +00:00
public smartdns = new plugins.smartdns.Smartdns({});
public async validate(emailArg: string): Promise<IEmailValidationResult> {
2020-06-18 21:04:52 +00:00
await this.fetchDomains();
2020-06-18 15:34:05 +00:00
const emailArray = emailArg.split('@');
const result = await this.smartdns.getRecord(emailArray[1], 'MX');
2020-06-18 21:04:52 +00:00
// console.log(emailArray);
// console.log(this.domainMap[emailArray[1]]);
2020-06-18 15:34:05 +00:00
return {
valid: !!result,
2020-06-18 21:04:52 +00:00
reason: 'todo',
disposable: this.domainMap[emailArray[1]] === 'disposable',
freemail: this.domainMap[emailArray[1]] === 'freemail'
2020-06-18 15:34:05 +00:00
};
}
2020-06-18 21:04:52 +00:00
public async fetchDomains() {
if (!this.domainMap) {
const localFileString = plugins.smartfile.fs.toStringSync(
plugins.path.join(paths.assetDir, 'domains.json')
);
const localFileObject = JSON.parse(localFileString);
let onlineFileObject: any;
try {
onlineFileObject = (
await plugins.smartrequest.getJson(
'https://raw.githubusercontent.com/romainsimon/emailvalid/master/domains.json'
)
).body;
this.domainMap = onlineFileObject;
console.log(
'smartmail EmailAddressValidator: Using online email list for email validation'
);
} catch (e) {
this.domainMap = localFileObject;
console.log(e);
console.log(
'smartmail EmailAddressValidator: Using local email list for email validation'
);
}
}
}
2020-06-18 15:34:05 +00:00
}