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

问题描述 投票:1回答:1

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

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<[email protected]>',
    '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(),但这没有帮助。此外,我在多个脚本运行之间没有得到任何输出。

php mysql email slim mailgun
1个回答
1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.