How do I validate an array of emails from a textbox before sending them to the wp_mail()
function?
$emails = 'test@test.com;test2@test2.com
email3@email3.com,email4@email4.com, email5.com';
$emails = preg_split('/[;,n]/', $emails);
$validEmails = array();
$subject = 'Hey Subject';
$message = 'I am a message';
foreach($emails as $key=>$value){
if (is_email($value)) {
array_push($validEmails, $value);
}
}
wp_mail($validEmails, $subject, $message, $headers);
The sample code above stops on the if (is_email())
condition. How can I validate each email in the array whichever way before sending to the mail function?
Are you aware you can pass a comma-separated string of email adresses to
wp_mail
?Then just throw that string into
wp_mail
âs first argument. Depending on exactly what you want to do with the emails, this approach may be sufficient.The
wp_mail
function internally relies on the PHPMailer library (unless you use a redefinedwp_mail
function). PHPMailer validates the email before adding it to the recipient list. Invalid emails will be skipped.