如何使用 SparkPost PHP API 一次发送多封邮件?

How to send multiple emails in one go with SparkPost PHP API?

我已经在 Spark 中成功使用了 PHP 传输端点post PHP API https://github.com/SparkPost/php-sparkpost#send-an-email-using-the-transmissions-endpoint with https://github.com/SparkPost/php-sparkpost#wait-synchronous 但现在我需要发送两封不同的电子邮件至两个不同的地址,在我程序的同一点。

似乎最明显的方法是使用异步方法 https://github.com/SparkPost/php-sparkpost#then-asynchronous 但我无法使用 post 端点。下面的代码。

或者有更好的方法吗?我不确定如何让同步代码一个接一个地执行两个单独的请求。

$promise1 = $sparky->transmissions->post([
            'content' => [
                'from' => ['name' => 'My Service', 'email' => 'noreply@myservice.com'],
                'subject' => 'Booking Confirmation',
                'html' => $html,
                ],
            'recipients' => [['address' => ['email' => 'myemail@gmail.com']]],
            'options' => ['open_tracking' => false, 'click_tracking' => false]
            ]);

      $promise1->then(
        function ($response) // Success callback
            {
            echo('success promise 1');
            },
        function (Exception $e) // Failure callback
            {
            dump($e->getCode()."<br>".$e->getMessage());
            }
        );

$promise2 = $sparky->transmissions->post([
           'content' => [
               'from' => ['name' => 'My Service', 'email' => 'noreply@myservice.com'],
               'subject' => 'Another Email',
               'html' => $html,
               ],
           'recipients' => [['address' => ['email' => 'anotheremail@gmail.com']]],
           'options' => ['open_tracking' => false, 'click_tracking' => false]
           ]);

      $promise2->then(
       function ($response) // Success callback
           {
           echo('success promise 2');
           },
       function (Exception $e) // Failure callback
           {
           dump($e->getCode()."<br>".$e->getMessage());
           }
       );

您已经为承诺履行和拒绝定义了处理程序。 但是需要履行或拒绝承诺才能调用处理程序。

由于您正在等待来自 SparkPost 的响应,因此您需要 wait() promise 对象。

$promise1->wait(); $promise2->wait();

读取 SparkPost Reference 的 Then(异步)部分的最后一行。

此外,如果您计划多个承诺,那么您可以使用 \GuzzleHttp\Promise\all() 组合所有承诺(如同一部分倒数第二行中的建议)