forked from EmailVerify/email-verify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·241 lines (201 loc) · 7.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
'use strict'
let validator = require('validator').isEmail,
dns = require('dns'),
net = require('net'),
logger = require('./logger.js').logger
const defaultOptions = {
port: 25,
sender: 'name@example.org',
timeout: 0,
fqdn: 'mail.example.org',
ignore: false
}
const errors = {
missing: {
email: 'Missing email parameter',
options: 'Missing options parameter',
callback: 'Missing callback function'
},
invalid: {
email: 'Invalid Email Structure'
},
exception: {
}
}
const infoCodes = {
finishedVerification: 1,
invalidEmailStructure: 2,
noMxRecords: 3,
SMTPConnectionTimeout: 4,
domainNotFound: 5,
SMTPConnectionError: 6
}
function optionsDefaults(options) {
if( !options ) options = {}
Object.keys(defaultOptions).forEach(function(key){
if(options && !options[key]) options[key] = defaultOptions[key]
})
return options
}
function dnsConfig(options){
try {
if( Array.isArray(options.dns) ) dns.setServers(options.dns)
else dns.setServers([options.dns])
}
catch(e){
throw new Error('Invalid DNS Options');
}
}
/*
Ideally you give the arguments as in the function signature. However, other valid signatures would include:
email,callback (using default options, not advised)
options,callback (using options.email for the email)
This is supporting the legacy (email,options,callback) as well as the (options,callback) that is promisify compatible
*/
module.exports.verify = function verify(email,options,callback){
let params = {}
let args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments))
args.forEach(function(arg){
if( typeof arg === 'string' ){
params.email = arg
}
else if( typeof arg === 'object' ){
params.options = arg
}
else if( typeof arg === 'function' ){
params.callback = arg
}
})
if( !params.email && params.options.email && typeof params.options.email === 'string' ) params.email = params.options.email
params.options = optionsDefaults(params.options)
if( !params.email ) throw new Error(errors.missing.email)
if( !params.options ) throw new Error(errors.missing.options)
if( !params.callback ) throw new Error(errors.missing.callback)
if( !validator(params.email) ) return params.callback(null, { success: false, info: 'Invalid Email Structure', addr: email, params: params, code: infoCodes.invalidEmailStructure })
if( params.options.dns ) dnsConfig(params.options)
logger.info("# Veryfing " + params.email)
startDNSQueries(params)
}
module.exports.verifyCodes = infoCodes;
function startDNSQueries(params){
let domain = params.email.split(/[@]/).splice(-1)[0].toLowerCase()
logger.info("Resolving DNS... " + domain)
dns.resolveMx(domain,(err,addresses) => {
if (err || (typeof addresses === 'undefined')) {
params.callback(err, { success: false, info: 'Domain not found', code: infoCodes.domainNotFound });
}
else if (addresses && addresses.length <= 0) {
params.callback(null, { success: false, info: 'No MX Records', code: infoCodes.noMxRecords });
}
else{
params.addresses = addresses
// Find the lowest priority mail server
let priority = 10000,
lowestPriorityIndex = 0
for (let i = 0 ; i < addresses.length ; i++) {
if (addresses[i].priority < priority) {
priority = addresses[i].priority
lowestPriorityIndex = i
logger.info('MX Records ' + JSON.stringify(addresses[i]))
}
}
params.options.smtp = addresses[lowestPriorityIndex].exchange
logger.info("Choosing " + params.options.smtp + " for connection")
beginSMTPQueries(params)
}
})
}
function beginSMTPQueries(params){
let stage = 0,
success = false,
response = '',
completed = false,
ended = false,
tryagain = false,
banner = ''
logger.info("Creating connection...")
let socket = net.createConnection(params.options.port, params.options.smtp)
let callback = (err,object) => {
callback = () => {} // multiple sources could call the callback, replace the function immediately to prevent it from being called twice
ended = true
return params.callback(err,object)
}
let advanceToNextStage = () => {
stage++
response = ''
}
if( params.options.timeout > 0 ){
socket.setTimeout(params.options.timeout,() => {
callback(null,{ success: false, info: 'Connection Timed Out', addr: params.email, code: infoCodes.SMTPConnectionTimeout, tryagain:tryagain })
socket.destroy()
})
}
socket.on('data', function(data) {
response += data.toString();
completed = response.slice(-1) === '\n';
if (completed) {
logger.server(response)
switch(stage) {
case 0: if (response.indexOf('220') > -1 && !ended) {
// Connection Worked
banner = response
var cmd = 'EHLO '+params.options.fqdn+'\r\n'
logger.client(cmd)
socket.write(cmd,function() { stage++; response = ''; });
}
else{
if (response.indexOf('421') > -1 || response.indexOf('450') > -1 || response.indexOf('451') > -1)
tryagain = true;
socket.end();
}
break;
case 1: if (response.indexOf('250') > -1 && !ended) {
// Connection Worked
var cmd = 'MAIL FROM:<'+params.options.sender+'>\r\n'
logger.client(cmd)
socket.write(cmd,function() { stage++; response = ''; });
}
else{
socket.end();
}
break;
case 2: if (response.indexOf('250') > -1 && !ended) {
// MAIL Worked
var cmd = 'RCPT TO:<' + params.email + '>\r\n'
logger.client(cmd)
socket.write(cmd,function() { stage++; response = ''; });
}
else{
socket.end();
}
break;
case 3: if (response.indexOf('250') > -1 || (params.options.ignore && response.indexOf(params.options.ignore) > -1)) {
// RCPT Worked
success = true;
}
stage++;
response = '';
// close the connection cleanly.
if(!ended) {
var cmd = 'QUIT\r\n'
logger.client(cmd)
socket.write(cmd);
}
break;
case 4:
socket.end();
}
}
})
socket.once('connect', function(data) {
logger.info("Connected")
})
socket.once('error', function(err) {
logger.error("Connection error")
callback( err, { success: false, info: 'SMTP connection error', addr: params.email, code: infoCodes.SMTPConnectionError, tryagain:tryagain })
})
socket.once('end', function() {
logger.info("Closing connection")
callback(null, { success: success, info: (params.email + ' is ' + (success ? 'a valid' : 'an invalid') + ' address'), addr: params.email, code: infoCodes.finishedVerification, tryagain:tryagain, banner:banner })
})
}