PHPMailer sending to multiple address separated by

2020-07-30 03:55发布

问题:

This question already has answers here:
Closed 5 years ago.

I am using PHPMailer to send emails, i use this to add the email address to send to:

$email->AddAddress($result["emailto"]);

my email addresses are coming from a database, it works fine but if the emailto column in my database looks like:

email1@domain.com,email2@domain.com

i get an error saying You must provide at least one recipient email address.

how can i get round this to be able to send to multiple addresses?

回答1:

You should explode it and then add the emails.

$addresses = explode(',', $result["emailto"]);
foreach ($addresses as $address) {
    $email->AddAddress($address);
}


回答2:

//Explode by comma so that we get an array of emails.
$emailsExploded = explode(",", $result["emailto"]);

//If the array isn't empty, loop through
if(!empty($emailsExploded)){
    foreach($emailsExploded as $emailAddress){
        $email->AddAddress(trim($emailAddress));
    }
} else{
    //This should not be the case.
    throw new Exception('No emails found!');
}


回答3:

You could do a explode on the , character and then do a foreach trough the array to add adresses.

$addresses = explode(',',$result["emailto"]);
foreach ( $addresses as $address ){
    $email->AddAddress($address);
}


回答4:

The problem is you have to do multiple calls to AddAddress or use a ; instead of a ,

Try doing this:

$email_array = explode(',', $result['emailto']);
for($i = 0; $i < count($email_array); $i++) {
    $email->AddAddress($email_array[$i]);
}


回答5:

You can try with an array, something like this :

$array = explode(",",$result["emailto"]);
$nb = count($array);
for ($i=0;$i<$nb;$i++) {
    $email->AddAddress($array[$i]);
}


回答6:

Just add foreach (explode($result["emailto"], ',') as $email) {$email->AddAddress($email);}