发送电子邮件给注册会员,没有重复


Sending email to registered members without repetation

我试图发送电子邮件给注册用户在一个网站,脚本工作正常,但有一个问题,它重复发送电子邮件。

例如:我们在数据库(Mysql)中有3个注册用户,PHP脚本首先选择电子邮件地址,然后将消息发送给它。

问题来了:1-它选择电子邮件1并发送消息给它(创建!)。2-它在电子邮件1旁边选择电子邮件2,然后,它将消息发送给他们两个。3-它选择电子邮件3,并发送消息到三个电子邮件(1,2和3)。

代码如下:

require 'Mail/PHPMailerAutoload.php';
$mail = new PHPMailer;
$limit=3;
$active="yes";
$stmt = $conn->prepare('select email,name from users where active=? limit ?');
$stmt->bind_param('si', $active,$limit);
$stmt->execute();
$i=0;
$stmt->bind_result($email,$name);
$arr = array();
while($stmt->fetch()) {
$row = array();
array_push($arr, $row);
include "compose_mail.php";}

compose_mail.php

$mail->isSMTP();  
$mail->CharSet = 'UTF-8';        // Set mailer      to use SMTP
$mail->Host = 'The Host';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP      authentication
$mail->Username = 'username';       // SMTP username
$mail->Password = 'password';       // SMTP password
$mail->SMTPSecure = 'ssl';         // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;            // TCP port to connect  to
$mail->From = 'email';
$mail->FromName = 'websit name';
$mail->addAddress($email);     // Add a recipient
$mail->isHTML(true);        // Set email format to  HTML
$mail->Subject = $title;
$mail->Body    = '
The HTML message';
if(!$mail->send()) {} else {}

你的while循环做了一些不必要的事情:

$stmt->bind_result($email,$name);
$arr = array();
while($stmt->fetch()) {
$row = array();
array_push($arr, $row);
include "compose_mail.php";}

包含"compose_mail.php";在每个循环中都包含,所以在3个循环之后,您将包含3个compose_mail.php.

在循环之前包含compose_mail.php,并将compose_mail.php更改为在其中包含函数调用:

function sendMail(your parameters) {
   Your mail code;
}

然后在while循环中调用这个函数。THis每次都有干净的参数,重复发送应该停止。

整个结构会变成这样:

require 'Mail/PHPMailerAutoload.php';
include "compose_mail.php";
$mail = new PHPMailer;
$limit=3;
$active="yes";
$stmt = $conn->prepare('select email,name from users where active=? limit ?');
$stmt->bind_param('si', $active,$limit);
$stmt->execute();
$i=0;
$stmt->bind_result($email,$name);
while($stmt->fetch()) {
  $mail = new PHPMailer;
  $arr = array();
  $row = array();
  array_push($arr, $row);
  sendMail($mail,$arr,$row);
}

这样每个循环都会重置所有参数,因此不可能有多个邮件。