1. Go to this page and download the library: Download lettr/lettr-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/ */
lettr / lettr-php example snippets
use Lettr\Lettr;
$lettr = Lettr::client('your-api-key');
// Send an email
$response = $lettr->emails()->send(
$lettr->emails()->create()
->from('[email protected]', 'Sender Name')
->to(['[email protected]'])
->subject('Hello from Lettr')
->html('<h1>Hello!</h1><p>This is a test email.</p>')
);
echo $response->requestId; // Request ID for tracking
echo $response->accepted; // Number of accepted recipients
// Sending quota (free tier teams only)
if ($response->quota !== null) {
echo $response->quota->monthlyLimit; // e.g. 3000
echo $response->quota->monthlyRemaining; // e.g. 2500
echo $response->quota->dailyLimit; // e.g. 100
echo $response->quota->dailyRemaining; // e.g. 75
}
use Lettr\Dto\Email\SendEmailData;
use Lettr\Dto\Email\EmailOptions;
use Lettr\ValueObjects\EmailAddress;
use Lettr\ValueObjects\Subject;
use Lettr\Collections\EmailAddressCollection;
$email = new SendEmailData(
from: new EmailAddress('[email protected]', 'Sender'),
to: EmailAddressCollection::from(['[email protected]']),
subject: new Subject('Hello'),
html: '<p>Email content</p>',
);
$response = $lettr->emails()->send($email);
use Lettr\ValueObjects\EmailAddress;
// Pass a string — validated as an email address
$response = $lettr->emails()->sendHtml(
from: '[email protected]',
to: '[email protected]',
subject: 'Hello',
html: '<p>HTML content</p>',
);
// Pass an EmailAddress — le.com',
to: ['[email protected]', '[email protected]'],
subject: 'Hello',
text: 'Plain text content',
);
// Template email — subject is optional; if omitted, the template's own subject is used
$response = $lettr->emails()->sendTemplate(
from: '[email protected]',
to: '[email protected]',
templateSlug: 'welcome-email',
templateVersion: 2,
projectId: 123,
substitutionData: ['name' => 'John'],
);
// Override the template's subject
$response = $lettr->emails()->sendTemplate(
from: '[email protected]',
to: '[email protected]',
templateSlug: 'welcome-email',
subject: 'Welcome!',
);
use Lettr\Dto\Email\Attachment;
$email = $lettr->emails()->create()
->from('[email protected]')
->to(['[email protected]'])
->subject('Document attached')
->html('<p>Please find the document attached.</p>')
// From file path
->attachFile('/path/to/document.pdf')
// With custom name and mime type
->attachFile('/path/to/file', 'custom-name.pdf', 'application/pdf')
// From binary data
->attachData($binaryContent, 'report.csv', 'text/csv')
// Using Attachment DTO
->attach(Attachment::fromFile('/path/to/image.png'));
$response = $lettr->emails()->send($email);
$response = $lettr->emails()->send(
$lettr->emails()->create()
->from('[email protected]')
->to(['[email protected]'])
->useTemplate('order-confirmation', version: 1, projectId: 123)
// subject() is optional when using a template — if omitted, the template must have a subject
// defined, otherwise the API will return an error
->subject('Your Order #{{order_id}}')
->substitutionData([
'order_id' => '12345',
'customer_name' => 'John Doe',
'items' => [
['name' => 'Product A', 'price' => 29.99],
['name' => 'Product B', 'price' => 49.99],
],
'total' => 79.98,
])
);
use Lettr\Exceptions\IdempotencyConflictException;
use Lettr\Exceptions\IdempotencyInProgressException;
$response = $lettr->emails()->send(
$lettr->emails()->create()
->from('[email protected]')
->to(['[email protected]'])
->subject('Your order')
->html($html),
idempotencyKey: 'order-confirmation-12345',
);
$response->replayed; // true when this replayed an earlier send — no second email went out
try {
$lettr->emails()->send($email, idempotencyKey: $key);
} catch (IdempotencyInProgressException $e) {
// The original send is still running. Retry with the SAME key.
sleep($e->retryAfter ?? 1);
} catch (IdempotencyConflictException $e) {
// That key was already used with a different payload. Retrying fails forever.
}
use Lettr\Dto\Email\ListScheduledEmailsFilter;
use Lettr\Enums\ScheduledEmailState;
$scheduled = $lettr->emails()->schedule(
$lettr->emails()->create()
->from('[email protected]')
->to(['[email protected]'])
->subject('Your weekly digest')
->html('<h1>This week</h1>')
->scheduledAt('2026-10-15T09:00:00Z')
);
$scheduled->requestId; // sch_01JQZ3... — use this to read it back or cancel it
$scheduled->state; // ScheduledEmailState::Scheduled
$scheduled->transmissionId; // null until the email is actually sent
// Read it back at any point — including after it was cancelled.
$scheduled = $lettr->emails()->getScheduled($scheduled->requestId);
if ($scheduled->isCancellable()) {
$cancelled = $lettr->emails()->cancelScheduled($scheduled->requestId);
$cancelled->state; // ScheduledEmailState::Cancelled
}
// List what is queued.
$page = $lettr->emails()->listScheduled(
ListScheduledEmailsFilter::create()
->status(ScheduledEmailState::Scheduled)
->perPage(25)
);
foreach ($page->scheduledEmails as $email) {
echo $email->requestId.' → '.$email->scheduledAt.PHP_EOL;
}
$page->hasMore();
// Check API health (no authentication echo $status->status; // 'ok'
echo $status->timestamp; // Timestamp object
echo $status->isHealthy(); // true/false
// Verify API key is valid and get team info
$auth = $lettr->health()->authCheck();
echo $auth->teamId; // Your team ID
echo $auth->timestamp; // Timestamp object
use Lettr\ValueObjects\EmailAddress;
use Lettr\ValueObjects\DomainName;
use Lettr\ValueObjects\RequestId;
use Lettr\ValueObjects\Timestamp;
// Email addresses with optional name
$email = new EmailAddress('[email protected]', 'User Name');
echo $email->address; // [email protected]
echo $email->name; // User Name
// Domain names (validated)
$domain = new DomainName('example.com');
// Request IDs
$requestId = new RequestId('req_abc123');
// Timestamps
$timestamp = Timestamp::fromString('2024-01-15T10:30:00Z');
echo $timestamp->toIso8601(); // ISO 8601 string
$timestamp->value; // DateTimeImmutable instance (not echoable directly)
echo $timestamp->format('Y-m-d'); // Custom format
use Lettr\Exceptions\ApiException;
use Lettr\Exceptions\TransporterException;
use Lettr\Exceptions\ValidationException;
use Lettr\Exceptions\NotFoundException;
use Lettr\Exceptions\UnauthorizedException;
use Lettr\Exceptions\ForbiddenException;
use Lettr\Exceptions\ConflictException;
use Lettr\Exceptions\QuotaExceededException;
use Lettr\Exceptions\RateLimitException;
use Lettr\Exceptions\InvalidValueException;
try {
$response = $lettr->emails()->send($email);
} catch (ValidationException $e) {
// Invalid request data (422)
echo "Validation failed: " . $e->getMessage();
} catch (UnauthorizedException $e) {
// Invalid API key (401)
echo "Authentication failed: " . $e->getMessage();
} catch (ForbiddenException $e) {
// Insufficient API key permissions (403)
echo "Forbidden: " . $e->getMessage();
} catch (NotFoundException $e) {
// Resource not found (404)
echo "Not found: " . $e->getMessage();
} catch (ConflictException $e) {
// Resource conflict (409)
echo "Conflict: " . $e->getMessage();
} catch (QuotaExceededException $e) {
// Sending quota exceeded (429) - monthly or daily limit reached
echo "Quota exceeded: " . $e->getMessage();
if ($e->quota !== null) {
echo $e->quota->monthlyLimit; // Total monthly limit
echo $e->quota->monthlyRemaining; // 0 when exhausted
echo $e->quota->monthlyReset; // Unix timestamp - start of next month
echo $e->quota->dailyLimit; // Total daily limit
echo $e->quota->dailyRemaining; // 0 when exhausted
echo $e->quota->dailyReset; // Unix timestamp - tomorrow midnight UTC
}
} catch (RateLimitException $e) {
// API rate limit exceeded (429) - too many requests per second
echo "Rate limited: " . $e->getMessage();
if ($e->rateLimit !== null) {
echo $e->rateLimit->limit; // Max requests per second
echo $e->rateLimit->remaining; // Remaining requests
echo $e->rateLimit->reset; // Unix timestamp when limit resets
}
if ($e->retryAfter !== null) {
sleep($e->retryAfter); // Seconds to wait before retrying
}
} catch (ApiException $e) {
// Other API errors
echo "API error ({$e->getCode()}): " . $e->getMessage();
} catch (TransporterException $e) {
// Network/transport errors
echo "Network error: " . $e->getMessage();
} catch (InvalidValueException $e) {
// Invalid value object (e.g., invalid email format)
echo "Invalid value: " . $e->getMessage();
}