1

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?

charlie
  • 1,356
  • 7
  • 38
  • 76

6 Answers6

8

You should explode it and then add the emails.

$addresses = explode(',', $result["emailto"]);
foreach ($addresses as $address) {
    $email->AddAddress($address);
}
casraf
  • 21,085
  • 9
  • 56
  • 91
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!');
}
Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
1

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);
}
Hans Dubois
  • 269
  • 1
  • 7
0

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]);
}
ddoor
  • 5,819
  • 9
  • 34
  • 41
0

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]);
}
guikk
  • 195
  • 5
0

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

JoDev
  • 6,633
  • 1
  • 22
  • 37