我正在使用 PHPMailer 发送电子邮件,我使用它来添加要发送到的电子邮件地址:
$email->AddAddress($result["emailto"]);
我的电子邮件地址来自数据库,它工作正常,但如果我的数据库中的 emailto 列看起来像:
email1@domain.com,email2@domain.com
我收到一条错误消息,提示您必须提供至少一个收件人电子邮件地址。
我怎样才能解决这个问题以便能够发送到多个地址?
您应该分解它,然后添加电子邮件。
$addresses = explode(',', $result["emailto"]);
foreach ($addresses as $address) {
$email->AddAddress($address);
}
//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!');
}
您可以对 , 字符进行爆炸,然后通过数组执行 foreach 以添加地址。
$addresses = explode(',',$result["emailto"]);
foreach ( $addresses as $address ){
$email->AddAddress($address);
}
您可以尝试使用数组,如下所示:
$array = explode(",",$result["emailto"]);
$nb = count($array);
for ($i=0;$i<$nb;$i++) {
$email->AddAddress($array[$i]);
}
只需添加foreach (explode($result["emailto"], ',') as $email) {$email->AddAddress($email);}
问题是您必须多次调用AddAddress
或使用 ; 代替 ,
尝试这样做:
$email_array = explode(',', $result['emailto']);
for($i = 0; $i < count($email_array); $i++) {
$email->AddAddress($email_array[$i]);
}