2013-10-17 71 views
1

a具有PHP郵件功能,該功能可將電子郵件發送到MySQL數據庫中的地址。PHP驗證由逗號分隔的電子郵件地址

在數據庫中,當有多個郵件地址時,用逗號分隔郵件地址。

if(filter_var($email_to, FILTER_VALIDATE_EMAIL)) 

但這只是一個電子郵件地址的作品,我怎麼能驗證多用逗號分隔:

我已經嘗試使用?

,如:

[email protected],[email protected] 

這裏是我的電子郵件功能:

require_once "/usr/local/lib/php/Mail.php"; 

      $from = $email_from; 
      $to = $email_to; 
      $subject = $email_subject; 
      $body = $email_body; 

      $host = "mail.domain.co.uk"; 
      $username = "[email protected]"; 
      $password = "*********"; 

      $headers = array ('From' => $from, 
       'To' => $to, 
       'Cc' => $cc, 
       'Subject' => $subject, 
       'Content-type' => 'text/html'); 
      $smtp = Mail::factory('smtp', 
       array ('host' => $host, 
      'auth' => true, 
      'username' => $username, 
      'password' => $password)); 

      $rec = $to.', '.$cc; 

      $mail = $smtp->send($rec, $headers, $body); 

我如何可以驗證在$並$ CC的逗號分隔值?

回答

1

您可以嘗試的電子郵件不會忽略首先使用逗號作爲分隔

$emails = explode(",", $email_to); 
$sendEmail = TRUE; 

foreach($emails as $email) { 
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
     $sendEmail = FALSE; 
     continue; 
    } 
} 

if($sendEmail === TRUE) { 
    //send email 
} 
0

拆分並分別驗證每個。

1

您需要先分離您的地址,然後逐個驗證它們。

使用explode()

// assuming $emails = '[email protected],[email protected]' 
$emails_arr = explode(',', $emails); // use comma as separator 

現在遍歷數組以得到不會忽略的一個陣列並應用當前的邏輯

foreach($emails_arr as $email) 
{ 
    if(filter_var($email, FILTER_VALIDATE_EMAIL)) 
    { 
    // do something 
    } 
} 
2

功能:

function getValidEmails($email_list) { 
    $valid_emails = array(); 
    if (-1 !== strpos($email_list, ',')) { 
     $email_list = explode(',', $email_list); 
     array_walk_recursive($email_list, function(&$email) { 
      $email = filter_var(trim($email), FILTER_VALIDATE_EMAIL); 
      if (false !== $email) { 
       $valid_emails[] = $email; 
      } 
     }); 
    } else { 
     $email = filter_var(trim($email_list), FILTER_VALIDATE_EMAIL); 
     if (false !== $email) { 
      $valid_emails[] = $email; 
     } 
    } 
    return $valid_emails; 
} 

用法:

$valid_emails = getValidEmails('[email protected],[email protected],[email protected]'); 
if (sizeof($valid_emails)) 
{ 
    $to  = implode(',', $valid_emails); 
    $subject = 'the subject'; 
    $message = 'hello'; 
    $headers = 'From: [email protected]' . "\r\n" . 
     'Reply-To: [email protected]' . "\r\n" . 
     'X-Mailer: PHP/' . phpversion() ."\r\n" . 
     'MIME-Version: 1.0' . "\r\n" . 
     'Content-type: text/html; charset=iso-8859-1' . "\r\n"; 

    mail($to, $subject, $message, $headers); 
} 
else { 
    // validation failed for email list 
} 

此函數可以使用單個電子郵件以及許多用逗號分隔的函數。

3

試試這個:

foreach(explode(',', $sEmailAddresses) AS $sEmailAddress) { 
    $bValid |= filter_var($sEmailAddress, FILTER_VALIDATE_EMAIL); 
} 

$sResult = ($bValid) ? 'Both are valid' : 'One of them are not'; 
相關問題