-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate_mail.php
635 lines (556 loc) · 13.8 KB
/
validate_mail.php
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
<?php
/**
* Validate Mail Class
*
* @license http://www.freebsd.org/copyright/freebsd-license.html FreeBSD Licence
* @author [email protected] - Roberto Nygaard - @topikito - github.com/topikito
* @version 1.0
*
* @example
* $emails = array(...);
* $ValidateMail = new ValidateMail();
* $result = $ValidateMail->checkEmails($emails);
*/
class ValidateMail
{
const MAX_READ_TIME = 6;
const MAX_CONN_TIME = 30;
const SOCKET_READ_SIZE = 2082;
const SOCKET_CODE_SUCCESS = 220;
const SMTP_CODE_ACCEPTED = 250;
const SMTP_CODE_EMAIL_REJECTED = 550;
const SMTP_CODE_SYNTAX_ERROR = 501;
const LEVEL_MORPHOLOGIC = 0;
const LEVEL_BLACKLIST = 1;
const LEVEL_DNS = 2;
const LEVEL_DNS_MX = 3;
const LEVEL_SMTP = 4;
const CHECK_SUCCESS = 1000;
const CHECK_ERROR_MORPHO = 1001;
const CHECK_ERROR_BLACKLIST = 1002;
const CHECK_ERROR_DNS = 1003;
const CHECK_ERROR_DNS_MX = 1004;
const CHECK_ERROR_SMTP = 1005;
const CHECK_ERROR_SERVER_UNKNOWN = 1099;
private $_errorCode = array(
1001 => 'MORPHOLOGICAL ERROR',
1002 => 'IN_BLACKLIST',
1003 => 'DNS_ERROR',
1004 => 'DNS_MX_ERROR',
1005 => 'SMTP_ERROR',
1099 => 'SERVER_ERROR'
);
/**
* Specifies if we match with the black list dictionary
* @var bool
*/
private $_enableBlackList = true;
/**
* Dictionary with domains known for being "trash emails"
* @var array
*/
protected $_emailDomainsBlackList = array(
'guerrillamail.com', 'guerrillamailblock.com',
'guerrillamail.net', 'guerrillamail.biz',
'guerrillamail.org', 'guerrillamail.de',
'sharklasers.com', 'spambox.us',
'rtrtr.com', '10minutemail.com',
'10minutemail.com', 'mailexpire.com',
'mailzilla.org', 'hidzz.com',
'mailcatch.com', 'incognitomail.org',
'tempemail.net', 'mintemail.com',
'spamgourmet.com', 'nobulk.com',
'spaml.com', 'spamify.com',
'mailnull.com', 'deadaddress.com',
'emailmiser.com', 'e4ward.com',
'sneakemail.com', 'mailme.lv',
'emailwarden.com', 'saynotospams.com',
'fakedemail.com', 'incognitomail.org',
'pookmail.com', 'mailinator.com',
'mailmetrash.com', 'thankyou2010.com',
'trash2009.com', 'mt2009.com',
'trashymail.com', 'mytrashmail.com',
'jetable.org', 'maileater.com',
'spamhole.com', 'kasmail.com',
'spammotel.com', 'shieldemail.com',
'teleworm.us', 'blockfilter.com',
'gishpuppy.com', 'spamex.com',
'shortmail.net', 'dontreg.com',
'tempomail.fr', 'tempemail.net',
'spamfree24.org', 'kasmail.com',
'spammotel.com', 'greensloth.com',
'spamspot.com', 'yopmail.com'
);
private $_sock;
private $_local;
private $_result;
private $_domain;
private $_domains;
private $_allValid = true;
private $_smtpPort = 25;
private $_fromUser = 'user';
private $_fromDomain = 'localhost';
private $_debugFlag = false;
/**
* Specifies the level of paranoia:
* 0 = Checks ONLY the morphology of the email
* 1 = Level 0 + BlackList checking
* 2 = Level 1 + Checks the DNS Records of the domain
* 3 = Level 2 + Checks the MX entries of the DNS of the domain
* 4 = Level 3 + Asks the SMTP server for the email
* @var int
*/
private $_levelOfParanoia = self::LEVEL_DNS_MX;
/**
* We add the email as invalid and specify the reason why its so.
* @param string $email
* @param string $reason
*/
protected function _markInvalidEmail($reason, $email = null)
{
if ($email === null)
{
$email = $this->_local . '@' . $this->_domain;
}
$this->_result[$email] = $reason;
$this->_allValid = false;
}
/**
*
* @param int $reason
* @param string[optional] $domain
* @return boolean
*/
protected function _markInvalidDomain($reason, $domain = null)
{
if ($domain === null)
{
$domain = $this->_domain;
}
foreach ($this->_domains[$domain] as $_local)
{
$email = $_local . '@' . $domain;
$this->_markInvalidEmail($reason, $email);
}
unset($this->_domains[$domain]);
return true;
}
/**
* This can be better than using a "strpos" method to get the local and the
* domain part because some emails can contain more than one '@'
*
* @param string $email
* @return array
*/
protected function _parseEmail($email)
{
$parts = explode('@', $email);
$domain = array_pop($parts);
$local = implode('@', $parts);
return array($local, $domain);
}
/**
* Set the Emails to validate
* @param $emails Array List of Emails
*/
protected function _setEmails($emails)
{
foreach ($emails as $email)
{
list($local, $domain) = $this->_parseEmail($email);
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
$this->_markInvalidEmail(self::CHECK_ERROR_MORPHO);
}
else
{
$this->_result[$email] = true;
if (!isset($this->_domains[$domain]))
{
$this->_domains[$domain] = array();
}
$this->_domains[$domain][] = $local;
}
}
return true;
}
/**
* Set the Email of the sender/validator
* @param $email String
*/
protected function _setSenderEmail($email)
{
list($this->_fromUser, $this->_fromDomain) = $this->_parseEmail($email);
return true;
}
/**
* Validate Email Addresses
* @param String $emails Emails to validate (recipient emails)
* @param String $sender Sender's Email
* @return Array Associative List of Emails and their validation results
*/
function _validateSMTP()
{
// query the MTAs on each Domain
$mxs = array();
$dnsRecords = $this->_getDomainMxEntries($this->_domain);
if ($dnsRecords === false)
{
return self::CHECK_ERROR_DNS;
}
list($hosts, $mxWeights) = $dnsRecords;
//Parse MX priorities
$numOfHosts = count($hosts);
for ($i = 0; $i < $numOfHosts; $i++)
{
$mxs[$hosts[$i]] = $mxWeights[$i];
}
asort($mxs);
//MX Entries. Last one the own domain
$mxs[] = $this->_domain;
$this->_debug('[New Domain] '. $this->_domain .': NS entries -> '. print_r($mxs,1));
$timeout = self::MAX_CONN_TIME / count($hosts);
while (list($host) = each($mxs))
{
// connect to SMTP server
$this->_debug('>$ telnet ' . $host . ' ' . $this->_smtpPort);
if ($this->_sock = fsockopen($host, $this->_smtpPort, $errno, $errstr, (float) $timeout))
{
stream_set_timeout($this->_sock, self::MAX_READ_TIME);
break;
}
}
// did we get a TCP socket
if ($this->_sock)
{
$reply = fread($this->_sock, self::SOCKET_READ_SIZE);
$this->_debug(' ~ '. $reply);
preg_match('/^([0-9]{3}) /ims', $reply, $matches);
$code = isset($matches[1]) ? $matches[1] : '';
$locals = $this->_domains[$this->_domain];
unset($this->_domains[$this->_domain]);
//Add the current local that have been popped
$locals[] = $this->_local;
$this->_debug('[Locals] -> '. print_r($locals,1));
if ($code != (string) self::SOCKET_CODE_SUCCESS)
{
foreach ($locals as $_local)
{
$currentEmail = $_local . '@' .$this->_domain;
$this->_markInvalidEmail(self::CHECK_ERROR_SERVER_UNKNOWN,$currentEmail);
}
return self::CHECK_SUCCESS;
}
$this->_tellSocket("HELO " . $this->_fromDomain);
$reply = $this->_tellSocket("MAIL FROM: <" . $this->_fromUser . '@' . $this->_fromDomain . ">");
preg_match('/^([0-9]{3}) /ims', $reply, $matches);
$code = isset($matches[1]) ? $matches[1] : '';
if ($code == (string) self::SMTP_CODE_SYNTAX_ERROR)
{
//Try as sending from the user
$reply = $this->_tellSocket("MAIL FROM: <" . $this->_local . '@' . $this->_domain . ">");
preg_match('/^([0-9]{3}) /ims', $reply, $matches);
$code = isset($matches[1]) ? $matches[1] : '';
if ($code != (string) self::SMTP_CODE_ACCEPTED)
{
//By default we will assume its ok
return self::CHECK_SUCCESS;
}
}
// ask for each recepient on this domain
foreach ($locals as $_local)
{
$currentEmail = $_local . '@' .$this->_domain;
$reply = $this->_tellSocket("RCPT TO: <" . $currentEmail . ">");
preg_match('/^([0-9]{3}) /ims', $reply, $matches);
$code = isset($matches[1]) ? $matches[1] : '';
if ($code == (string) self::SMTP_CODE_EMAIL_REJECTED)
{
//We will JUST mark as invalid those where the server
//tells us as so
$this->_markInvalidEmail(self::CHECK_ERROR_SMTP,$currentEmail);
}
}
$this->_tellSocket('quit');
$this->_debug('');
fclose($this->_sock);
}
return self::CHECK_SUCCESS;
}
/**
* Sends information to the socket
* @param string $msg
* @return string
*/
protected function _tellSocket($msg)
{
fwrite($this->_sock, $msg . "\r\n");
$reply = fread($this->_sock, self::SOCKET_READ_SIZE);
$this->_debug("[O <-]\n" . $msg);
$this->_debug("[I ->]\n" . $reply);
return $reply;
}
/**
* Retrieves the A or CNAME entries of a domain
* @param string $domain
* @return boolean
*/
protected function _checkDomainHasEntries($domain)
{
return (checkdnsrr($domain) ||
checkdnsrr($domain, 'A') ||
checkdnsrr($domain, 'CNAME'));
}
/**
* Retrieves the MX entries of a domain
* @param string $domain
* @return boolean|array
*/
protected function _getDomainMxEntries($domain)
{
$hosts = array();
$mxweights = array();
$result = getmxrr($domain, $hosts, $mxweights);
if ($result)
{
return array($hosts, $mxweights);
}
return false;
}
public function enableDebug()
{
$this->_debugFlag = true;
}
public function disableDebug()
{
$this->_debugFlag = false;
}
/**
* Prints the debug information
* @param string $text
* @param bool $nl
*/
protected function _debug($text, $nl = true)
{
if ($this->_debugFlag === true)
{
echo htmlentities($text);
if ($nl)
{
echo '<br />' . "\n";
}
flush();
}
}
/**
* Constructor
*
* @param string $emails
* @return string
*/
public function __construct($emails = array())
{
if (!empty($emails))
{
$this->checkEmails($emails);
}
return $this;
}
/**
* Returns the results of the validation
* @return bool|array
*/
public function getResult()
{
if (empty($this->_result))
{
return null;
}
if ($this->_allValid)
{
$this->_result = true;
}
return $this->_result;
}
/* * ******** Setters for private/protected atributes ********* */
/**
* Sets the black list domain array
*
* @param type $emailDomainsBlackList
* @return boolean|string
*/
public function setEmailDomainsBlackList($emailDomainsBlackList = array())
{
if (empty($emailDomainsBlackList))
{
return false;
}
if (!is_array($emailDomainsBlackList))
{
$emailDomainsBlackList = (array) $emailDomainsBlackList;
}
$this->_emailDomainsBlackList = array_flip($emailDomainsBlackList);
return $this;
}
/**
* Enables the usage of black listing for domains
*
* @return string
*/
public function enableBlackList()
{
$this->_enableBlackList = true;
return $this;
}
/**
* Disables the usage of black listing for domains
*
* @return string
*/
public function disableBlackList()
{
$this->_enableBlackList = false;
return $this;
}
/* * ******** Getters for private/protected atributes ********* */
/**
* Returns the domain black list
*
* @return array
*/
public function getEmailDomainsBlackList()
{
return $this->_emailDomainsBlackList;
}
/**
* Returns the state of the black list check
*
* @return type
*/
public function getBlackListState()
{
return $this->_enableBlackList;
}
/**
* Returns the relation with the ID and the string code error
* @return array
*/
public function getErrorCodes()
{
return $this->_errorCode;
}
/** Public functions * */
/**
* Checks if the local (user) of the email is valid
*
* @param string $local
* @return boolean
*/
public function checkLocal($local = '')
{
if ($this->_levelOfParanoia >= self::LEVEL_SMTP)
{
return $this->_validateSMTP();
}
return self::CHECK_SUCCESS;
}
/**
* Checks if the domain of the email is valid
*
* @param string $domain
* @return boolean
*/
public function checkDomain($domain = '')
{
if (empty($domain))
{
$domain = $this->_domain;
}
if ($this->_levelOfParanoia >= self::LEVEL_BLACKLIST)
{
if ($this->_enableBlackList)
{
$host = explode('.', $domain);
while (count($host) > 2)
{
array_shift($host);
}
$host = implode('.', $host);
if (isset($this->_emailDomainsBlackList[$host]))
{
return self::CHECK_ERROR_BLACKLIST;
}
}
}
if ($this->_levelOfParanoia >= self::LEVEL_DNS) //CHECK DNS
{
if (!$this->_checkDomainHasEntries($domain))
{
return self::CHECK_ERROR_DNS;
}
}
if ($this->_levelOfParanoia >= self::LEVEL_DNS_MX) //CHECK MAIL ENTRIES
{
if (!$this->_getDomainMxEntries($domain))
{
return self::CHECK_ERROR_DNS_MX;
}
}
return self::CHECK_SUCCESS;
}
public function setCheckLevel($level)
{
if (!is_int($level))
{
return false;
}
$this->_levelOfParanoia = $level;
return $this;
}
/**
* Checks if an email is valid by checking the local and the domain
*
* @param array $emails
* @return type
*/
public function checkEmails($emails)
{
if (is_string($emails))
{
$emails = (array) $emails;
}
//Initialize the emails
$this->_setEmails($emails);
//Load the blacklist as a key array so its faster to find
$this->_emailDomainsBlackList = array_flip($this->_emailDomainsBlackList);
//Asume the result is already valid
$this->_allValid = true;
$domains = array_keys($this->_domains);
foreach ($domains as $this->_domain)
{
$checkCode = $this->checkDomain($this->_domain);
if ($checkCode > self::CHECK_SUCCESS)
{
//This domain aint valid, mark as not valid all the emails
$this->_markInvalidDomain($checkCode);
continue;
}
while (!empty($this->_domains[$this->_domain]))
{
//Check the local part of the email
$this->_local = array_pop($this->_domains[$this->_domain]);
$email = $this->_local . '@' . $this->_domain;
$checkCode = $this->checkLocal($this->_local);
if ($checkCode > self::CHECK_SUCCESS)
{
$this->_markInvalidEmail($checkCode, $email);
}
}
}
if ($this->_allValid)
{
return true;
}
return $this->_result;
}
}