# PHP SDK

Install the Mailset PHP SDK, send email, verify webhooks and handle errors, with examples that run.

- **Every public command**: 238 commands, each a typed method
- **No dependencies**: Nothing else to install beside it
- **Typed throughout**: Readonly classes, checked by PHPStan
- **Retries built in**: Two more tries, and a send never doubles
- **Timeouts per try**: 30 seconds a try, then tried again
- **Idempotency keys**: A send repeated with its key goes once

## Requirements

- PHP 8.1 or later

## Install

Composer:

```bash
composer require mailset-app/php
```

## Create a client

One client holds one `MAILSET_KEY`. Make it when your server starts and use it for every call.

### Example

```php
<?php

require 'vendor/autoload.php';

// One client for the whole server. It reads MAILSET_KEY
// from the environment; ['key' => …] passes one instead.
// Nothing is sent until you call send.
$mailset = new Mailset\Client();
```

### Pass the key in

Where your app keeps its secrets elsewhere, hand the key to the client yourself. A token goes the same way.

```php
require 'vendor/autoload.php';

// From your secret store or config, never in the code.
// Or ['token' => …] with an API token.
$key = $config['mailset_key'];
$mailset = new Mailset\Client(['key' => $key]);
```

### Options

Everything has a default. Name a credential, an org, how long a try may take and how often a call is tried again, only where yours differ.

```php
<?php

require 'vendor/autoload.php';

use Mailset\Approval;

$mailset = new Mailset\Client([
    // Or 'token' => getenv('MAILSET_TOKEN'),
    // for an API token.
    'key' => (string) getenv('MAILSET_KEY'),
    // Where Mailset is. A key names its own, and
    // MAILSET_API overrides it.
    'baseUrl' => 'https://mailset.app',
    // The org commands are about, for a person in
    // more than one.
    'org' => 'org_7c2e9a4f',
    // Each try may take 10 seconds. A network
    // failure, a timeout or a 5xx is tried 3 more
    // times, waiting longer each time.
    'timeout' => 10,
    'maxRetries' => 3,
    // A command that needs a passkey waits for
    // someone to approve it.
    'onApproval' => function (Approval $approval): void {
        $url = $approval->url;
        echo "Approve with your passkey: {$url}", PHP_EOL;
    },
]);

print_r($mailset->key->check());
```

More: [Authentication](https://mailset.app/docs/authentication)

## Send

Send one message and get its receipt. A message Mailset refuses is an error with a code, never a silent drop.

### Example

```php
<?php

require 'vendor/autoload.php';

// Reads MAILSET_KEY from the environment.
$mailset = new Mailset\Client();

$sent = $mailset->send([
    'from' => 'Acme <hello@example.com>',
    'to' => 'ana@example.org',
    'subject' => 'Your Acme code',
    'text' => 'Your code is 123456.',
    'html' => '<p>Your code is <b>123456</b>.</p>',
    'deliverBy' => '10m',
]);

echo $sent->id, ' ', $sent->status, PHP_EOL;
```

More: [Give sign-in codes a deadline](https://mailset.app/docs/recipes/deadlines), [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes), [Handle skipped recipients](https://mailset.app/docs/recipes/skipped), [Guide for PHP](https://mailset.app/send-email/php)

## Send many

Send several messages in one call and get one result per message, in the same order. A refused message never stops the rest.

### Example

```php
<?php

require 'vendor/autoload.php';

use Mailset\Sent;

// Reads MAILSET_KEY from the environment.
$mailset = new Mailset\Client();

$results = $mailset->sendMany([
    [
        'from' => 'Acme <hello@example.com>',
        'to' => 'ana@example.org',
        'subject' => 'Your invoice',
        'text' => 'Invoice 8842 is ready.',
    ],
    [
        'from' => 'Acme <hello@example.com>',
        'to' => 'ben@example.org',
        'subject' => 'Your invoice',
        'text' => 'Invoice 8843 is ready.',
    ],
]);

foreach ($results as $result) {
    if ($result instanceof Sent) {
        echo $result->id, ' ', $result->status, PHP_EOL;
        continue;
    }
    $code = $result->error->errorCode;
    error_log("{$result->messageId} {$code}");
}
```

More: [Send many messages at once](https://mailset.app/docs/recipes/batches)

## Promotional email

Send a newsletter or an offer with `mode: 'promotional'`. `{{mailset_unsubscribe}}` is a placeholder Mailset fills in for each message, with a signed one-click unsubscribe link unique to that recipient and that message. You never generate the link, and Mailset adds the matching `List-Unsubscribe` and `List-Unsubscribe-Post` headers itself.

### Example

```php
<?php

require 'vendor/autoload.php';

// Reads MAILSET_KEY from the environment.
$mailset = new Mailset\Client();

$text = <<<'TEXT'
    Three new things this month.

    Leave this list: {{mailset_unsubscribe}}
    TEXT;

$html = <<<'HTML'
    <p>Three new things this month.</p>
    <a href="{{mailset_unsubscribe}}">Leave this list</a>
    HTML;

$sent = $mailset->send([
    'from' => 'Acme News <news@news.example.com>',
    'to' => 'ana@example.org',
    'subject' => 'What shipped in March',
    'text' => $text,
    'html' => $html,
    'mode' => 'promotional',
]);

echo $sent->id, ' ', count($sent->skipped), PHP_EOL;
```

### What Ana receives

Headers Mailset adds:

```text
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
```

The text part:

```text
Three new things this month.

Leave this list: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
```

The HTML part:

```html
<p>Three new things this month.</p>
<a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Leave this list</a>
```

A sample link. Mailset makes a new one for every message.

### What Ana receives without the placeholder

The text part:

```text
Three new things this month.

Unsubscribe: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
```

The HTML part:

```html
<p>Three new things this month.</p><p><a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Unsubscribe</a></p>
```

Mailset adds the last line of each part. The headers are the same.

More: [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes), [Handle skipped recipients](https://mailset.app/docs/recipes/skipped)

## Idempotency

Name a send with `idempotencyKey`, and sending it again after a timeout or a crash can’t send it twice.

### Example

```php
<?php

require 'vendor/autoload.php';

// Reads MAILSET_KEY from the environment.
$mailset = new Mailset\Client();

$receipt = [
    'from' => 'Acme <hello@example.com>',
    'to' => 'ana@example.org',
    'subject' => 'Your receipt',
    'text' => 'Thanks for your order.',
    'idempotencyKey' => 'receipt-8842',
];

$first = $mailset->send($receipt);
// After a timeout or a crash, send it again.
// The same key answers the first receipt,
// and nothing goes out twice.
$again = $mailset->send($receipt);

var_dump($first->id === $again->id);
```

More: [Retry without sending twice](https://mailset.app/docs/recipes/retries)

## Check the key

Ask what the key may do now. Call it when your server starts and once a day: each call keeps the key alive.

### Example

```php
<?php

require 'vendor/autoload.php';

use Mailset\Types\SendingState;

// Reads MAILSET_KEY from the environment.
$mailset = new Mailset\Client();

// When the server starts, and once a day.
$status = $mailset->key->check();

if ($status->paused !== null) {
    error_log("Paused: {$status->paused}");
}
$until = intdiv($status->expiresAt, 1000);
echo 'Works until ', gmdate('c', $until), PHP_EOL;

// A state this SDK doesn't know yet is text.
$text = fn ($s) => is_string($s) ? $s : $s->value;

// A mailbox key sends as its mailbox.
foreach ($status->mailboxes as $box) {
    if ($box->sending !== SendingState::Ready) {
        $state = $text($box->sending);
        error_log("{$box->address}: {$state}");
    }
}
// A domain key sends as the addresses it names.
foreach ($status->domains as $domain) {
    $as = $domain->from === null
        ? 'any address'
        : implode(', ', $domain->from);
    echo "{$domain->name} sends as {$as}", PHP_EOL;
    if ($domain->sending !== SendingState::Ready) {
        $state = $text($domain->sending);
        error_log("{$domain->name}: {$state}");
    }
}
```

More: [Keep a key alive](https://mailset.app/docs/recipes/keys)

## Delivery search

Look up what became of the mail this key sent, one line per recipient. For a support question or a nightly check.

### Example

```php
<?php

require 'vendor/autoload.php';

// Reads MAILSET_KEY from the environment.
$mailset = new Mailset\Client();

// Did Ana get her receipt?
$page = $mailset->delivery->search([
    'recipient' => 'ana@example.org',
    'since' => '2026-11-30',
]);

foreach ($page->lines as $line) {
    echo $line->status, ' ', $line->reason, PHP_EOL;
}
// Pass `next` back as `cursor` for the page after.
echo $page->next, PHP_EOL;
```

More: [Handle bounces](https://mailset.app/docs/recipes/bounces)

## Webhooks

Check that a request came from Mailset and read its events. It needs no key and no client, so a service that only receives events uses it alone.

### Example

```php
<?php

require 'vendor/autoload.php';

use Mailset\Events\BouncedEvent;
use Mailset\MailsetException;
use Mailset\Webhooks;

try {
    $events = Webhooks::verify(
        (string) file_get_contents('php://input'),
        getallheaders(),
        (string) getenv('MAILSET_HOOK_SECRET'),
    );
} catch (MailsetException $error) {
    http_response_code(401);
    exit($error->errorCode);
}
foreach ($events as $event) {
    if (!$event instanceof BouncedEvent) {
        continue;
    }
    if ($event->bounce->kind === 'hard') {
        error_log("Stop writing to {$event->recipient}");
    }
}
// 2xx once the events are kept.
// Until then Mailset posts the batch again.
http_response_code(204);
```

### In a web framework

The signature covers the body exactly as it arrived. Read the raw body before anything parses it, and hand that to the check: a body parsed as JSON and written out again no longer matches.

```php
<?php

// routes/api.php: a Laravel route for your hook.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Mailset\Events\BouncedEvent;
use Mailset\MailsetException;
use Mailset\Webhooks;

Route::post('/mailset', function (Request $request) {
    try {
        // The signature covers the body as it came:
        // read it raw. $request->all() or ->json()
        // would lose the bytes it was made over.
        $events = Webhooks::verify(
            $request->getContent(),
            $request->headers,
            config('services.mailset.hook_secret'),
        );
    } catch (MailsetException $error) {
        return response($error->errorCode, 401);
    }
    foreach ($events as $event) {
        if (!$event instanceof BouncedEvent) {
            continue;
        }
        if ($event->bounce->kind === 'hard') {
            $to = $event->recipient;
            logger()->info("Stop writing to {$to}");
        }
    }

    // 2xx once the events are kept. Until then
    // Mailset posts the batch again.
    return response()->noContent();
});
```

More: [Webhooks](https://mailset.app/docs/webhooks), [Handle bounces](https://mailset.app/docs/recipes/bounces), [Guide for Laravel](https://mailset.app/send-email/laravel), [Guide for Symfony](https://mailset.app/send-email/symfony)

## Errors

Every refusal is one kind of error. Branch on its `code`, which never changes, and show its `message` to people.

### Example

```php
<?php

require 'vendor/autoload.php';

use Mailset\Exception\RateLimitException;
use Mailset\MailsetException;

// Reads MAILSET_KEY from the environment.
$mailset = new Mailset\Client();

try {
    $mailset->send([
        'from' => 'Acme <hello@example.com>',
        'to' => 'ana@example.org',
        'subject' => 'Your Acme code',
        'text' => 'Your code is 123456.',
        'deliverBy' => '10m',
    ]);
} catch (RateLimitException $error) {
    $at = intdiv($error->retryAt ?? 0, 1000);
    echo 'Try at ', gmdate('c', $at), PHP_EOL;
} catch (MailsetException $error) {
    if ($error->refusal === 'recipient') {
        echo 'Ask them to check their address.', PHP_EOL;
    } else {
        $code = $error->errorCode;
        error_log("{$code} {$error->getMessage()}");
    }
}
```

### Retries and timeouts

A network failure or a 5xx answer is tried again, twice unless you set `maxRetries`, waiting longer each time. One try may take 30 seconds unless you set `timeout`. A refusal is never tried again: the same request gets the same answer.

More: [Errors and limits](https://mailset.app/docs/errors)

## Build the message yourself

Get the message a send would build, without sending it: for a queue of your own, or a call to the API from another service.

### Example

```php
<?php

require 'vendor/autoload.php';

$message = Mailset\Message::build([
    'from' => 'Acme <hello@example.com>',
    'to' => 'ana@example.org',
    'subject' => 'Your Acme code',
    'text' => 'Your code is 123456.',
]);

// The `data` that messages.submit takes.
$data = base64_encode($message->raw);

echo $message->messageId, ' ', strlen($data), PHP_EOL;
```

More: [messages.submit](https://mailset.app/docs/api/messages#messages.submit)

## Version and licence

This page is for version 0.7.0 of the PHP SDK.

You may use the SDK and change it in your own apps and services, to call Mailset. You may not publish it or pass it on, by itself or inside another library.

Something missing, or not working as this page says? Ask us at https://mailset.app/support, or run `mailset feedback "<message>"` in a terminal.

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content