Send with

Send email with PHP

Any PHP version with the cURL extension can call the API. Using Laravel? See Send with Laravel.

With cURL

<?php

function send_email(array $email, ?string $idempotencyKey = null): string
{
    $headers = [
        'Authorization: Bearer ' . getenv('ROBUSTEMAIL_API_KEY'),
        'Content-Type: application/json',
    ];
    if ($idempotencyKey) {
        $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
    }

    $ch = curl_init('https://robustemail.com/api/v2/emails');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => json_encode($email),
        CURLOPT_TIMEOUT => 15,
    ]);
    $body = json_decode(curl_exec($ch), true);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($status >= 400) {
        throw new RuntimeException($body['name'] . ': ' . $body['message']);
    }

    return $body['id'];
}

$id = send_email([
    'from' => 'Acme <hello@acme.com>',
    'to' => 'delivered@sandbox.robustemail.dev',
    'subject' => 'Welcome to Acme',
    'html' => '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
], 'welcome-user-1042');

With Guzzle

use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://robustemail.com/api/v2/',
    'headers' => ['Authorization' => 'Bearer ' . getenv('ROBUSTEMAIL_API_KEY')],
    'timeout' => 15,
]);

$res = $client->post('emails', [
    'headers' => ['Idempotency-Key' => 'invoice-2041'],
    'json' => [
        'from' => 'Acme Billing <billing@acme.com>',
        'to' => 'jane@example.com',
        'subject' => 'Your invoice #2041',
        'html' => '<p>Your invoice is attached.</p>',
        'attachments' => [[
            'filename' => 'invoice-2041.pdf',
            'content' => base64_encode(file_get_contents('invoice-2041.pdf')),
            'content_type' => 'application/pdf',
        ]],
    ],
]);

$id = json_decode((string) $res->getBody(), true)['id'];

Guzzle throws an exception for 4xx and 5xx responses; the JSON body holds name and message.

Next