gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:22:02 25 4
gpt4 key购买 nike

我们有一个 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 拆分行.

关于PHP 邮件脚本运行多次(使用 Mailgun),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com