PHP code example of lettermint / lettermint-php

1. Go to this page and download the library: Download lettermint/lettermint-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lettermint / lettermint-php example snippets


use Lettermint\Lettermint;

$lettermint = new Lettermint(sendingToken: getenv('LETTERMINT_PROJECT_TOKEN'));

$result = $lettermint->emails->send([
    'from' => 'Acme <[email protected]>',
    'to' => ['[email protected]'],
    'subject' => 'Welcome to Acme',
    'html' => '<p>Thanks for signing up.</p>',
    'text' => 'Thanks for signing up.',
]);

echo $result->message_id, ' ', $result->status; // "…", "pending"

$lettermint = new Lettermint(
    sendingToken: getenv('LETTERMINT_PROJECT_TOKEN'),
    teamToken: getenv('LETTERMINT_TEAM_TOKEN'),
);

$lettermint = new Lettermint(getenv('LETTERMINT_TOKEN'));
$lettermint = new Lettermint(getenv('LETTERMINT_TOKEN'), timeout: 10);

$welcome = $lettermint->emails->compose()
    ->from('Acme <[email protected]>')
    ->subject('Welcome to Acme')
    ->tags([['name' => 'campaign', 'value' => 'welcome']]);

$welcome->to('[email protected]')->html('<p>Hi Jane</p>')->send();
$welcome->to('[email protected]')->html('<p>Hi John</p>')->send();

$email = $lettermint->emails->compose()->from('[email protected]')->to($user->email)->subject('Your invoice');
if ($user->accountant !== null) {
    $email = $email->cc($user->accountant);
}
$email->html($invoiceHtml)->send();

$lettermint->emails->send([
    'from' => 'Acme <[email protected]>',
    'to' => ['[email protected]'],
    'reply_to' => ['[email protected]'],
    'subject' => 'Your order has shipped',
    'html' => $html,
    'metadata' => ['order_id' => '1234'],
]);

$results = $lettermint->emails->sendBatch([
    ['from' => '[email protected]', 'to' => ['[email protected]'], 'subject' => 'Hi Jane', 'text' => 'Hello'],
    $welcome->to('[email protected]')->html('<p>Hi John</p>'),
]);

$results = $lettermint->emails->sendBatch([
    ['from' => '[email protected]', 'to' => ['[email protected]'], 'subject' => 'Hi Jane', 'text' => 'Hello', 'idempotency_key' => 'welcome-jane'],
    $welcome->to('[email protected]')->html('<p>Hi John</p>')->idempotencyKey('welcome-john'),
]);

$lettermint->emails->send($message, idempotencyKey: "order-{$order->id}-confirmation");
$builder->send(idempotencyKey: 'welcome-jane');
$lettermint->emails->sendBatch($messages, idempotencyKey: 'newsletter-2026-10');

$result = $lettermint->emails->compose()
    ->from('[email protected]')
    ->to('[email protected]')
    ->subject('Your trial ends tomorrow')
    ->text('…')
    ->scheduledAt(new DateTimeImmutable('+1 day'))
    ->send();

if ($result->status === \Lettermint\Types\MessageStatus::SCHEDULED) {
    echo $result->scheduled_at;
}

$lettermint->messages->reschedule($result->message_id, ['scheduled_at' => '2026-10-20T09:00:00Z']);
$lettermint->messages->cancel($result->message_id);

$resent = $lettermint->messages->resend($messageId);
$resent = $lettermint->messages->resend($messageId, ['recipients' => ['[email protected]']], idempotencyKey: "resend-{$messageId}");

echo $resent->message_id; // the new message

$result = $lettermint->emails->compose()
    ->from('[email protected]')
    ->to('[email protected]')
    ->subject('Test')
    ->text('Test')
    ->sandboxResult('hard_bounced')
    ->send();

var_dump($result->sandbox, $result->sandbox_result); // true, "hard_bounced"

use Lettermint\Attachment;

$lettermint->emails->compose()
    ->from('[email protected]')
    ->to('[email protected]')
    ->subject('Your invoice')
    ->html('<img src="cid:logo"> Your invoice is attached.')
    ->attach(Attachment::fromPath('/path/to/invoice.pdf', contentType: 'application/pdf'))
    ->attach(new Attachment('report.csv', $csvBytes, 'text/csv'))
    ->attach(Attachment::fromBase64('logo.png', $logoBase64, contentId: 'logo'))
    ->send();

$lettermint = new Lettermint(teamToken: getenv('LETTERMINT_TEAM_TOKEN'));

$domain = $lettermint->domains->create(['domain' => 'acme.com']);
$lettermint->domains->verifyDnsRecords($domain->id);

$project = $lettermint->projects->create(['name' => 'Production']);
echo $project->api_token; // the new project's sending token, shown once

$stats = $lettermint->stats->retrieve(['from' => '2026-10-01', 'to' => '2026-10-31']);
$html = $lettermint->messages->html('message-id');

$invite = $lettermint->team->invites->create([
    'email' => '[email protected]',
    'role_id' => 'role-id',
    'project_access' => ['scope' => 'selected', 'project_ids' => ['project-id']],
]);
$lettermint->team->invites->revoke($invite->id);

use Lettermint\Types\RbacPermission;

$role = $lettermint->team->createRole([
    'name' => 'Support',
    'description' => 'Reads messages.',
    'permissions' => [RbacPermission::MESSAGES_READ],
]);
$lettermint->team->deleteRole($role->id, ['replacement_role_id' => 'other-role-id']);

$message = $lettermint->messages->retrieve('message-id');
echo $message->subject;
foreach ($message->to ?? [] as $recipient) {
    echo $recipient->email;
}
$message['subject'];   // array access works too
$message->toArray();   // the JSON as the API sent it
$message->has('spam_score'); // whether an optional field is present

$page = $lettermint->domains->list([
    'page' => ['size' => 30],
    'filter' => ['status' => 'verified'],
    'sort' => ['-created_at'],
]);

echo count($page), ' ', $page->next_cursor;
$next = $lettermint->domains->list(['page' => ['size' => 30, 'cursor' => $page->next_cursor]]);

foreach ($lettermint->messages->iterate(['filter' => ['status' => 'hard_bounced']]) as $message) {
    echo $message->id, ' ', $message->subject, PHP_EOL;
}

$result = $lettermint->analytics([
    'metrics' => ['delivered', 'bounced', 'delivery_rate'],
    'from' => '2026-10-01',
    'to' => '2026-10-31',
    'timezone' => 'Europe/Amsterdam',
]);

var_dump($result->data->summary?->metrics->delivery_rate); // 0.9836, or null when there is no data
var_dump($result->meta->partial, $result->meta->effective_to);

$query = [
    'metrics' => ['delivered', 'bounced'],
    'tric' => 'bounced', 'direction' => 'desc'],
    'limit' => 200,
];

$rows = [];
foreach ($lettermint->analyticsPages($query) as $page) {
    array_push($rows, ...($page->data->breakdown ?? []));
    if ($page->pagination->truncated) {
        error_log('More groups exist than the API ranks.');
    }
}

use Lettermint\Exceptions\ApiException;
use Lettermint\Exceptions\RateLimitException;
use Lettermint\Exceptions\TimeoutException;
use Lettermint\Exceptions\ValidationException;

try {
    $lettermint->emails->send($message, idempotencyKey: $key);
} catch (ValidationException $e) {
    report($e->getMessage(), $e->errors);
} catch (RateLimitException $e) {
    sleep($e->retryAfter ?? 1); // then retry with the same idempotency key
} catch (TimeoutException $e) {
    // The outcome is unknown. Retry with the same idempotency key.
} catch (ApiException $e) {
    report($e->status, $e->errorCode, $e->getMessage());
}

use Lettermint\Exceptions\WebhookVerificationException;
use Lettermint\Webhook;

$webhook = new Webhook(getenv('LETTERMINT_WEBHOOK_SECRET'));

try {
    $payload = $webhook->verify($request->getContent(), $request->headers);
} catch (WebhookVerificationException $e) {
    return new Response('Invalid signature', 400);
}

echo $payload->event; // "message.delivered"
$payload->data;      // the event data

$payload = $webhook->verify((string) $request->getBody(), $request);
bash
composer