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

时间:2018-08-28 21:07:15

标签: php sparkpost

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

似乎最明显的方法是使用异步方法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());
           }
       );

1 个答案:

答案 0 :(得分:1)

您已经为诺言实现和拒绝定义了处理程序。 但是,必须履行或拒绝诺言才能调用处理程序。

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

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

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

此外,如果您要计划多个诺言,则可以使用\GuzzleHttp\Promise\all()组合所有诺言(如本节第二行的建议)