I've successfully used the PHP transmissions endpoint in Sparkpost PHP API https://github.com/SparkPost/php-sparkpost#send-an-email-using-the-transmissions-endpoint with https://github.com/SparkPost/php-sparkpost#wait-synchronous but now I need to send two different emails to two different addresses, at the same point in my program.
Seemed like the obvious way was to use the asynchronous method https://github.com/SparkPost/php-sparkpost#then-asynchronous but I can't get this working with the post endpoint. Code below.
Or is there a better way? I wasn't sure how to make the synchronous code do two separate requests one after the other.
$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());
}
);
You've defined handlers for promise fulfillment and rejection. But the promise requires to be fulfilled or rejected to invoke the handlers.
Since you're waiting for response from SparkPost, you need to wait()
on the promise object.
$promise1->wait();
$promise2->wait();
Read last line in Then (Asynchronous) Section of SparkPost Reference.
Also, if you're planning for multiple promises then you may use \GuzzleHttp\Promise\all()
to combine all promises ( as suggested in second last line of same section )