Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

Reputation: 3074

How to handle invalide email exception in cakephp?

I have a list of array. There are some invalid emails inside an array. i.e:

$to = array('[email protected]','sas dsad .com');

Here [email protected] is an valid mail but sas dsad .com is not a valid email. So if I want to send email with this recipients ($to) there will be occurred a fatal error for sas dsad .com. So How can I ignore these invalid email?

N.B: I am using cakephp 2.6.7

Upvotes: 1

Views: 756

Answers (2)

Inigo Flores
Inigo Flores

Reputation: 4469

CakeEmail throws SocketException if the email address is not well constructed. Just catch the exception and ignore it.

Option 1: Send multiple emails

$email = new CakeEmail();
$to = array('[email protected]','sas dsad .com');  

foreach ($to as $emailAddress)  {
    try {
        $email->to($emailAddress);
        $email->send();
    } catch(SocketException $e) {
        //Do nothing  
    }

    $email->reset();
}

Option 2: Send a single email

$email = new CakeEmail();
$to = array('[email protected]','sas dsad .com');  

foreach ($to as $emailAddress)  {
    try {
        $email->addTo($emailAddress);
    } catch(SocketException $e) {
        //Do nothing  
    }
}

$email->send();

See CakeEmail::addTo().

Upvotes: 2

Er.KT
Er.KT

Reputation: 2860

You can remove all invalid email with following code :

<?php
$len=count($array);
for ($i=0;$i<$len;$i++)
  if (preg_match('^[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+(?:[a-z]{2,4}|museum|travel)$/i',$array[$i]))
      echo $array[$i];
?>

Remove invalid email format in PHP

Upvotes: 0

Related Questions