PHP 邮件脚本运行多次(使用 Mailgun)

PHP mailing script runs multiple time (using Mailgun)

我们有一个 PHP 脚本,它应该向所有符合特定条件的用户发送电子邮件。该脚本使用 Mailgun 来处理邮件。该脚本适用于少量记录(大约 500 条或更少),但是,如果记录变得太多(比如 1000、2000),脚本不会结束,而是运行多次(用户两次收到相同的电子邮件或三次)。

require __DIR__ . '/../vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = new Mailgun('our-private-key');
$mgClient1= new Mailgun('our-public-key');
$domain = "our.domain";

// 1. Connect to database

$pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'psw');
$pdo->exec('SET NAMES "utf8"');


// 2. Query users table for any records where field "endDate" < the current time

$query = "SELECT userId, firstName, email FROM users WHERE endDate <= now() AND sub = 0";
$expiredQuery = $pdo->prepare($query);
$expiredQuery->execute();

$expired = $expiredQuery->fetchAll(PDO::FETCH_OBJ);

if (empty($expired)) {
    echo 'There are no records to unsubscribe.';
    exit();
}


// 3. If found, loop through results and get the "uId"; save users to a users array

$ids = [];
$usernames = [];
$emails = [];

foreach ($expired as $user) {
  $id = $user->uId;
  $username = $user->fName;
  $useremail = $user->email;
  array_push($ids, $id);
  array_push($usernames, $username);
  array_push($emails, $useremail);
}


// 4. Send email to users

$counter = 0;

foreach ($emails as $email) {

  # Issue the call to the client.
  $resultVer = $mgClient1->get("address/validate", array('address' => $email));
  # is_valid is 0 or 1
  $isValid = $resultVer->http_response_body->is_valid;


  if (!$isValid) {
    echo "Not delivered: " . $email . "<br>"; 
    $counter++;
    continue;
  }

  $firstname = $usernames[$counter];

  # Build recipient email
  $rec_msg = 'Hi '.$firstname.'... etc etc';

  # Send mail to recipient
  $result = $mgClient->sendMessage($domain, array(
    'from'    => 'Sender<Sender@sender.com>',
    'to'      => $email,
    'subject' => 'An email',
    'html'    => $rec_msg,

  ), array(
    'inline'  => array('http://www.oursite.com/images/mail_header.jpg', 'http://www.oursite.com/images/footer.jpg')
  ));

  # Increment the counter
  $counter++;
}


// 6. Send notification

echo "The following users were sent an email <br>" . implode(", ", $emails);
die();

我尝试在末尾添加 die() 但这没有帮助。此外,我在多个脚本运行之间没有得到任何输出。

两个阻止邮件脚本一次 运行 多次,我建议使用锁定组件,如 symfony/lock

另一个问题是您尝试一次发送的电子邮件数量。尝试将邮件数量分成更小的垃圾邮件,例如500一次。您可以使用 SQL LIMIT x,y 过滤器,或者获取所有行并使用 array_chunk.

拆分行