Send transactional email from PHP and Laravel

PHP runs a large share of Kenyan websites and business systems. This guide shows how to send email through JMSURF Mail from plain PHP with cURL and from Laravel with its HTTP client.

Before you start

  • A JMSURF Mail account with a verified domain (quick start).
  • An API key in an environment variable called JMSURF_MAIL_KEY (never in code you commit).
  • PHP 7.4 or newer with the cURL extension (installed on almost every host, including cPanel).

Plain PHP: a small reusable function

jmsurf_mail.php
<?php
function jmsurf_mail(array $email, ?string $idempotencyKey = null): array {
    $headers = [
        "Authorization: Bearer " . getenv("JMSURF_MAIL_KEY"),
        "Content-Type: application/json",
    ];
    if ($idempotencyKey) $headers[] = "Idempotency-Key: " . $idempotencyKey;

    $ch = curl_init("https://api.jmsurfmail.co.ke/api/v1/emails");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => json_encode($email),
    ]);
    $raw = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $data = json_decode($raw ?: "{}", true) ?: [];
    if ($status < 200 || $status >= 300) {
        throw new RuntimeException(($data["code"] ?? "error") . ": " . ($data["error"] ?? "HTTP $status"));
    }
    return $data; // ["id" => "…", "status" => "sent"]
}
Use it
<?php
require "jmsurf_mail.php";

$result = jmsurf_mail([
    "from" => "Savannah Shop <[email protected]>",
    "to" => "[email protected]",
    "subject" => "Your order #1024 is confirmed",
    "html" => "<h1>Asante!</h1><p>We are packing your order.</p>",
    "text" => "Asante! We are packing your order.",
    "reply_to" => "[email protected]",
    "tags" => ["order"],
], "order-1024-confirmation");

echo $result["id"];

Templates and attachments

PHP
jmsurf_mail([
    "from" => "Savannah Shop <[email protected]>",
    "to" => $customerEmail,
    "template" => "invoice",
    "variables" => ["name" => $name, "invoice" => "INV-2041", "amount" => "KES 12,000"],
    "attachments" => [[
        "filename" => "INV-2041.pdf",
        "content" => base64_encode(file_get_contents($pdfPath)),
        "content_type" => "application/pdf",
    ]],
], "invoice-INV-2041");

Placeholders such as {{name}} are filled and escaped for you; see templates. Attachments are base64, up to 20 per email and 10 MB in total.

Laravel

Add the key to .env and config/services.php:

.env and config/services.php
# .env
JMSURF_MAIL_KEY=jm_live_paste_your_key_here

// config/services.php
'jmsurf_mail' => [
    'key' => env('JMSURF_MAIL_KEY'),
    'url' => 'https://api.jmsurfmail.co.ke/api/v1',
],
app/Services/JmsurfMail.php
<?php
namespace App\Services;

use Illuminate\Support\Facades\Http;

class JmsurfMail
{
    public static function send(array $email, ?string $idempotencyKey = null): array
    {
        $req = Http::withToken(config('services.jmsurf_mail.key'))
            ->acceptJson()
            ->timeout(20);
        if ($idempotencyKey) {
            $req = $req->withHeaders(['Idempotency-Key' => $idempotencyKey]);
        }
        return $req->post(config('services.jmsurf_mail.url') . '/emails', $email)
            ->throw()   // throws on 4xx/5xx; the JSON body has "error" and "code"
            ->json();
    }
}
Use it in a job or controller
use App\Services\JmsurfMail;

JmsurfMail::send([
    'from' => 'YourApp <[email protected]>',
    'to' => $user->email,
    'template' => 'welcome',
    'variables' => ['name' => $user->name],
], "welcome-{$user->id}");

Send from a queued job so a slow network never holds up a page. The Idempotency-Key makes queue retries safe.

Laravel's Mail facade and SMTP

JMSURF Mail is an HTTPS API. There is no SMTP login for customers yet, so apps that can only send through SMTP need a few lines of code that call the API instead. Your own SMTP server can be added as a backup route in Settings.

If your code already uses Mail::to()->send(), the simplest path is to render the mailable to HTML ((new OrderShipped($order))->render()) and pass it as html to the service above.

Errors

Status and codeMeaning
400 invalid_jsonThe body is not JSON.
401 invalid_api_keyMissing, wrong or revoked key.
403 domain_not_verifiedThe From domain is not verified on your account.
403 insufficient_scopeA send-only key tried to read logs or manage domains.
413 too_largeThe email is over 10 MB.
422 validation_errorA field is missing or wrong; the message says which.
429 quota_exceededDaily or monthly allowance used.
429 rate_limitedMore than 20 requests a second on this key.
502 send_failedEvery delivery route refused it; the message says why.

Send your first email today

Free plan with 100 emails a month, no card needed. Questions? WhatsApp or call +254 712 504 593, or email [email protected].