PHP
<?phpfunction spacepost_send(array $email, ?string $idempotencyKey = null): array { $headers = [ 'Authorization: Bearer ' . getenv('SPACEPOST_API_KEY'), 'Content-Type: application/json', ]; if ($idempotencyKey) { $headers[] = 'Idempotency-Key: ' . $idempotencyKey; } $ch = curl_init('https://api.spacepost.dev/emails'); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => json_encode($email), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, ]); $body = json_decode(curl_exec($ch), true); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status >= 300) { throw new RuntimeException("{$body['name']}: {$body['message']}"); } return $body; // ['id' => '...']}
print_r(spacepost_send([ 'from' => 'Acme <hello@acme.com>', 'to' => ['delivered@test.spacepost.dev'], 'subject' => 'Hello from PHP', 'html' => '<p>It works.</p>',]));composer require guzzlehttp/guzzle<?phprequire 'vendor/autoload.php';
$client = new GuzzleHttp\Client([ 'base_uri' => 'https://api.spacepost.dev', 'headers' => ['Authorization' => 'Bearer ' . getenv('SPACEPOST_API_KEY')], 'http_errors' => false, 'timeout' => 15,]);
$res = $client->post('/emails', ['json' => [ 'from' => 'Acme <hello@acme.com>', 'to' => ['delivered@test.spacepost.dev'], 'subject' => 'Hello from Guzzle', 'html' => '<p>It works.</p>',]]);
echo $res->getStatusCode(), ' ', $res->getBody();使用 Laravel?SMTP 中继无需修改代码。