将存储在mysql数据库中的地址的电子邮件发送给多个收件人

时间:2016-02-11 09:46:21

标签: php mysql

在下面的示例中,如果我取消注释$ emailList,则会发送电子邮件。来自数据库的回声显示“email1 @ yahoo.com,email2 @ yahoo.com”

如果我在数据库中只保留一个地址,那么它也可以。不确定地址之间的逗号是否导致问题。我不确定为什么现在发送的电子邮件包含来自数据库的多个地址的信息。

$emailId = mysql_query("Select * from email_group WHERE id = 1");
while($rowEmail = mysql_fetch_assoc($emailId))
{
$emailList = $rowEmail['email']; 
} 

// the message
$msg = "Test Message";

// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);

echo $emailList;
//$emailList = "email1@yahoo.com,email2@yahoo.com";

// send email
mail($emailList,"Test Subject",$msg); 

4 个答案:

答案 0 :(得分:3)

你可以试试这个

$emailId = mysql_query("Select * from email_group WHERE id = 1");

$emailList = [];
while($rowEmail = mysql_fetch_assoc($emailId))
{
$emailList[] = $rowEmail['email']; 
} 

// the message
$msg = "Test Message";

// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);

// send email
mail(implode(", ", $emailList),"Test Subject",$msg); 

答案 1 :(得分:0)

使用您的代码$emailList = "email1@yahoo.com,email2@yahoo.com,";

问题是最后一个逗号。这对代码添加了额外的逗号,

mail(email1@yahoo.com,email2@yahoo.com,,"Test Subject",$msg); 

// Which leads to an error.

因此,使用代码

删除电子邮件字符串中的最后一个逗号
$emailList = rtrim($emailList, ",");

现在$emailList就像,

$emailList = "email1@yahoo.com,email2@yahoo.com";

另一种方法

分解电子邮件列表并逐个发送。像,

$email_ids = explode(",",$emailList);

foreach($email_ids as $email){
  mail($email,"Test Subject",$msg); 
}

答案 2 :(得分:0)

所有你需要修改你的电子邮件地址,因为它在字符串的末尾有一个逗号。试试吧。

$emailId = mysql_query("Select * from email_group WHERE id = 1");
while($rowEmail = mysql_fetch_assoc($emailId))
{
$emailList = $rowEmail['email']; 
} 

// the message
$msg = "Test Message";

// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);

echo $emailList = rtrim($emailList, ",");
//$emailList = "email1@yahoo.com,email2@yahoo.com";

// send email
mail($emailList,"Test Subject",$msg);

答案 3 :(得分:0)

试试这个:

<?php
$emailId = mysql_query("Select * from email_group WHERE id = 1");
while($rowEmail = mysql_fetch_assoc($emailId))
{
    $emailList[] = $rowEmail['email'];
}

// the message
$msg = "Test Message";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);    
if(!empty($emailList)) {
    $emails = implode(',',$emailList);
    // send email
    mail($emails,"Test Subject",$msg);
}
?>