如何通过phpmailer在PHP和MySQL中发送多个电子邮件

时间:2012-05-11 17:58:39

标签: php mysql phpmailer

我有问题。当我点击发送按钮时,只有zxc@hotmail.com收到消息。

如何改变?我使用Gmail SMTP发送。

数据库中有2条记录:

这是我的代码:

include "phpmailer/class.phpmailer.php";
$host = "localhost";
$user = "root";
$pass = "root";
$db = "mailTest";

mysql_connect($host, $user, $pass);
mysql_select_db($db);

$query = "SELECT email FROM list";

$recordset = mysql_query($query);
$row_recordset = mysql_fetch_assoc($recordset);
$tota_row_recordset = mysql_num_rows($recordset);
$msg = strip_tags($_POST['msg']);
$mail= new PHPMailer(); //建立新物件 
while($row = mysql_fetch_array($recordset))
{
    $to = $row['email'];
    $mail->AddAddress($to, "Test Message"); 
}      
$mail->IsSMTP();    
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";     
$mail->Port = 465;      
$mail->CharSet = "big5";
$mail->Subject = "Test Message";     
$mail->Username = "xxxxxx";    
$mail->Password = "xxxxxx";   
$mail->Body = "$msg";
$mail->IsHTML(true);           
if(!$mail->Send()) {      
echo "Mailer Error: " . $mail->ErrorInfo;       
} else {      
header('Location: index.php');
}

3 个答案:

答案 0 :(得分:4)

使用此循环,您可以在每次迭代时覆盖收件人,因此只有最后一个留下来接收电子邮件:

while($row = mysql_fetch_array($recordset))
{
    $to = $row['email'];
}
$mail = new PHPMailer(); 

将您的代码更改为

$mail = new PHPMailer(); // create object FIRST
while($row = mysql_fetch_array($recordset))
{
    $to = $row['email'];
    $mail->AddAddress($to, "Test Message"); // add each DB entry to list of recipients
}

答案 1 :(得分:3)

尝试以下方法:

while($row = mysql_fetch_array($recordset))
{
    $to = $row['email'];
    $mail= new PHPMailer();
    $mail->IsSMTP();

    $mail->SMTPAuth = true;

    $mail->SMTPSecure = "ssl";

    $mail->Host = "smtp.gmail.com";

    $mail->Port = 465;

    $mail->CharSet = "big5";

    $mail->Subject = "Test Message";

    $mail->Username = "xxxxxx";

    $mail->Password = "xxxxxx";

    $mail->Body = "$msg";

    $mail->IsHTML(true);

    $mail->AddAddress($to, "Test Message");

    if(!$mail->Send()) {

    echo "Mailer Error: " . $mail->ErrorInfo;
    }
}    

答案 2 :(得分:0)

if(isset($_POST['sbmit']))
{
    for($i=0;$i<count($_POST['email_address']);$i++)
    {

          $to = $_POST['email_address'][$i];
          echo $to."<br />";
          $subject = 'Thank you for Subscribing';
          $message = $_POST['news'];
          $headers = 'From: dhakalneil@gmail.com' . "\r\n" .
          'Reply-To: xyz@hotmail.com' . "\r\n" .
          'X-Mailer: PHP/' . phpversion();


         echo $_POST['email_address'][$i]."<br />";
         ini_set("SMTP","smtp.ntc.net.np" );
         ini_set('sendmail_from', 'dhakalneil@gmail.com');
         if( mail($to,$subject,$message,$headers))
         {
                echo "Mail has been sent to admin<br />";
         }
         else
         {
                echo "Mail could not been sent";
         } 

    }
}


?>