a have a PHP Mail function which sends emails to addresses from a MySQL Database.
In the database, the email addresses are separated by a comma when there are multiple.
i have tried using:
if(filter_var($email_to, FILTER_VALIDATE_EMAIL))
but this only works for one email address, how can i validate multiple separated by a comma?
like:
[email protected],[email protected]
here is my email function:
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);
how can i validate the comma separated values in the $to and $cc?
Try this:
foreach(explode(',', $sEmailAddresses) AS $sEmailAddress) {
$bValid |= filter_var($sEmailAddress, FILTER_VALIDATE_EMAIL);
}
$sResult = ($bValid) ? 'Both are valid' : 'One of them are not';
function:
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;
}
usage:
$valid_emails = getValidEmails('[email protected],bbb@bbb,[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
}
this function will work with single email as well as many, separated by comma.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With