Валидный e-mail

Проверка валидности емайл адреса

PHP:
function emailCheck($emailStr)
{
  if($emailStr=='') return '';

  // The following is the list of known TLDs that an e-mail address must end with.

  $knownDomsPat= '^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$';

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

  $emailPat= '/^(.+)@(.+)$/';

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */

  $specialChars= '\\(\\)><@,;\/:\\\\\\\"\\.\\[\\]';

/* The following string represents the range of characters allowed in a
username or domainname.  It really states which chars aren't allowed.*/

  $validChars= '[^\\s' . $specialChars . ']';

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

  $quotedUser= '(\"[^\"]*\")';

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

  $ipDomainPat= '/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/';

/* The following string represents an atom (basically a series of non-special characters.) */

  $atom= $validChars . '+';

/* The following string represents one word in the typical username.
For example, in [email]john.doe@somewhere.com[/email], john and doe are words.
Basically, a word is either an atom or quoted string. */

  $word= '(' . $atom . '|' . $quotedUser . ')';

// The following pattern describes the structure of the user

  $userPat= '/^' . $word . '(\\.' . $word . ')*$/';

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

  $domainPat= '/^' . $atom . '(\\.' . $atom . ')*$/';

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

  if (!preg_match($emailPat,$emailStr,$matchArray))
  {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

    return 'Email address seems incorrect (check @ and .)';
  }
  $user=$matchArray[1];
  $domain=$matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

  for ($i=0; $i<strlen($user); $i++) 
    if (ord(substr($user,$i,1))>127) return 'The username in email contains invalid characters.';
  for ($i=0; $i<strlen($domain); $i++) 
    if (ord(substr($domain,$i,1))>127) return 'This domain name contains invalid characters.';

// user is not valid
  if (!preg_match($userPat,$user)) return 'The username in email does not seem to be valid.';

/* if the e-mail address is at an IP address (closed in [] ) make sure the IP address is valid. */

  if (preg_match($ipDomainPat,$domain,$IPArray))
  {
    for ($i=1;$i<=4;$i++) 
      if ($IPArray[$i]>255 OR $IPArray[$i]=='') return 'Destination IP address is invalid!';
    return '';
  }

// Domain is symbolic name.  Check if it's valid.

  $atomPat= '/^' . $atom . '$/';
  $domArr=split('\.',$domain);
  $len=count($domArr);
  for ($i=0;$i<$len;$i++) 
    if (!preg_match($atomPat,$domArr[$i])) return 'The domain name does not seem to be valid.';

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */

  if (strlen($domArr[count($domArr)-1])!=2 && !ereg($knownDomsPat,$domArr[count($domArr)-1]))
    return 'The email address must end in a well-known domain or two letter country, or IP closed in [].';

// Make sure there's a host name preceding the domain.

  if ($len<2) return 'This email address is missing a hostname!';

// If we've gotten this far, everything's valid!
  return '';
}

Добавлено через 20 минут
В файле-обработчике формы производим следующие действия:

1. Разбиваем введенный адрес на имя пользователя и имя хоста
(для адреса tabyretkin@bla-bla.ru:
tabyretkin - это пользователь
bla-bla.ru - это хост)

PHP:
$email_arr = explode("@" , $email);
$emailhost = $email_arr[1];

2. Далее следует "гвоздь программы" - функция getmxrr(), которая возвращает набор записей MX (Mail Exchange - почтового обмена). MX-запись содержится в DNS.

PHP:
if (!getmxrr($emailhost, $mxhostsarr))
{
  echo "На адрес $email нельзя отправить почту!";
  exit;
}

3. При желании можно выдать список хостов, через которые возможна отправка писем. Этот список находится в массиве $mxhostsarr

PHP:
  echo "На $email возможна отправка писем через следующие хосты: ";   
  for ($i=0; $i < count($mxhostsarr); $i++)
    echo $mxhostsarr[$i]." ";
 
"/\\A(?:^([a-z0-9][a-z0-9_\\-\\.\\+]*)@([a-z0-9][a-z0-9\\.\\-]{0,63}\\.([a-z]{2,6}))$)\\z/i"
 
подскажите, а можно как то проверить точнее, т.е. не просто на соответствие шаблону через регексп и не на существование домена, а именно валидность мыла? как то находил статьи что через посылку SMTP RCPT email и через VRFY email но у меня серв возвращает: 252 2.5.2 Cannot VRFY user; try RCPT to attempt delivery (or try finger)

а RCPT добавляет все имайлы на отправку даже не валидные.
 
для этой функции должны быть предустановлены фильтры, если их нет на хостинге то и работать не будет!
Installation
The filter extension is enabled by default as of PHP 5.2.0. Before this time an experimental PECL extension was used, however, the PECL version is no longer recommended or updated.

таким образом если хостер не совсем отстой, то эта штука там будет :-]
 
У меня проблема наоборот-p403_formbuilder чтобы настроить,нужно Create New Recipient.Ввожу нормальный e-mail,получаю The email address you have entered is invalid ....В чём проблема?...Раньше сталкивался,но решения сейчас найти не могу...
 
Назад
Сверху