אהלן,
החלטתי לשתף אתכם בחלק ממחלקה שכתבתי, החלק הספציפי הזה מוודא את תקינות האימייל.
PHP קוד:
public function validAddress($addr) {
if(filter_var($addr,FILTER_VALIDATE_EMAIL) == false) {
throw new Exception("כתובת האימייל אינה תקינה");
return false;
}
$domain = substr($addr,strpos($addr,'@')+1);
$mxhosts = $this->MXQuery($domain);
if($mxhosts == false) {
throw new Exception("לא נמצאו שרתי אימייל למשלוח, וודא שכתובת האימייל תקינה");
return false;
}
$ok = false;
foreach($mxhosts as $host) {
if(!$this->openSocket($host)) // open socket to mail server
continue;
$ok = $this->checkHost($host, $addr); // check email address in mail server
$this->closeSocket(); // close connection to mail server
break;
}
if($ok == false) {
throw new Exception("שרת הדואר של הלקוח דיווח שכתובת האימייל אינה תקינה");
return false;
}
return true;
}
private function openSocket($host) {
// open socket to $host on port 25 (SMTP)
// define timeout of 5 seconds
// return false on failure or true on success
$this->sock = fsockopen($host, 25, $errno, $errstr, 5);
if(!$this->sock)
return false;
stream_set_timeout($this->sock, 5);
return true;
}
private function closeSocket() {
// close open socket $this->sock
// before fclose call nicly to "quit"
fwrite($this->sock,"quit\r\n");
fclose($this->sock);
}
private function sockMsg($msg) {
// send $msg to open socket ($this->sock)
// fetch reply from $this->sock
// return 3 first chars (supposed to be 3 digits)
fwrite($this->sock, "{$msg}\r\n");
$reply = fread($this->sock,2082);
return substr($reply,0,3); // return code (3 digits)
}
private function checkHost($host, $addr) {
// do full communication with selected mail SMTP server
// return false on failure (if we not recived wanted responses) or true otherwise
$res = fread($this->sock,2082);
if(substr($res,0,3) != '220')
return false;
// send "helo hi"
if($this->sockMsg("helo hi") != '250')
return false;
// send "mail from"
if($this->sockMsg("mail from: <your@domain.com>") != '250')
return false;
// send "rcpt to"
if($this->sockMsg("rcpt to: <{$addr}>") != '250')
return false;
return true;
}
private function MXQuery($domain) {
// do MX Query for selected domain
// return an array of MX records of this domain
if(!getmxrr($domain,$mxhosts))
return false;
return $mxhosts;
}
מי שרוצה יכול להחליף את בדיקת הכתובת עצמה (התנאי הראשון) במשהו קצת יותר רציני ב-regex.
אפשר גם למיין את הmxhosts לפי העדיפות שלהם למרות שלא ממש נחוץ.
בנוסף, הפונקציה checkHosts מחזירה false במידה ולא התקבלה התוצאה הרצויה, אם מישהו רוצה הוא יכול להרחיב אותה שתחזיר בדיוק מה השגיאה שהתקבלה (נניח תיבת האימייל של המקבל מלאה, תיבת האימייל לא נמצאה וכו').
תהנו
