PHP邮件脚本多次运行(使用Mailgun)
我们有一个PHP脚本,tht应该向符合特定条件的所有用户发送电子邮件。脚本使用Mailgun处理邮件。脚本可以很好地处理少量记录(大约500条或更少),但是,如果记录太多(比如1000条、2000条),脚本不会结束,而是运行多次用户会收到两到三次相同的电子邮件PHP邮件脚本多次运行(使用Mailgun),php,mysql,email,slim,mailgun,Php,Mysql,Email,Slim,Mailgun,我们有一个PHP脚本,tht应该向符合特定条件的所有用户发送电子邮件。脚本使用Mailgun处理邮件。脚本可以很好地处理少量记录(大约500条或更少),但是,如果记录太多(比如1000条、2000条),脚本不会结束,而是运行多次用户会收到两到三次相同的电子邮件 require __DIR__ . '/../vendor/autoload.php'; use Mailgun\Mailgun; # Instantiate the client. $mgClient = new Mailgun('o
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();
我试着在最后加上骰子,但没用。另外,在多次脚本运行之间,我没有得到任何输出。如果有两种方法可以防止邮件脚本一次运行多次,我建议使用锁定组件,如 另一个问题是你试图一次发送的电子邮件数量。尝试将邮件数量分成更小的垃圾,例如,一次500封。您可以使用SQL限制x、y筛选器,也可以获取所有行并使用拆分行