PHP code example of lettr / lettr-laravel

1. Go to this page and download the library: Download lettr/lettr-laravel 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-laravel example snippets


use Illuminate\Support\Facades\Mail;
use App\Mail\Lettr\WelcomeEmail;

// Using a generated Mailable
Mail::to('[email protected]')->send(new WelcomeEmail($data));

// Or send templates inline
Mail::lettr()->to('[email protected]')->sendTemplate('welcome-email', substitutionData: $data);

'mailers' => [
    // ... other mailers

    'lettr' => [
        'transport' => 'lettr',
    ],
],

use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeEmail;

Mail::to('[email protected]')->send(new WelcomeEmail());

use Lettr\Laravel\Facades\Lettr;

$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

use Illuminate\Support\Facades\Mail;
use App\Mail\OrderConfirmation;

// Send using Mailable
Mail::to('[email protected]')
    ->cc('[email protected]')
    ->bcc('[email protected]')
    ->send(new OrderConfirmation($order));

Mail::raw('Plain text email content', function ($message) {
    $message->to('[email protected]')
            ->subject('Quick Update');
});

Mail::send('emails.welcome', ['user' => $user], function ($message) {
    $message->to('[email protected]')
            ->subject('Welcome!');
});

// Use Lettr for this specific email
Mail::mailer('lettr')
    ->to('[email protected]')
    ->send(new TransactionalEmail());

// Uses default mailer
Mail::to('[email protected]')
    ->send(new MarketingEmail());



namespace App\Mail;

use Lettr\Laravel\Mail\LettrMailable;
use Illuminate\Mail\Mailables\Envelope;

class WelcomeEmail extends LettrMailable
{
    public function __construct(
        public string $userName,
        public string $activationUrl,
    ) {}

    public function build(): static
    {
        return $this
            ->template('welcome-email', version: 2)
            ->substitutionData([
                'user_name' => $this->userName,
                'activation_url' => $this->activationUrl,
            ]);
    }
}

use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeEmail;

Mail::to('[email protected]')
    ->send(new WelcomeEmail(
        userName: 'John',
        activationUrl: 'https://example.com/activate/abc123'
    ));

class OrderConfirmation extends LettrMailable
{
    public function __construct(
        public Order $order,
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: "Order #{$this->order->id} Confirmed",
        );
    }

    public function build(): static
    {
        return $this
            ->template('order-confirmation')
            ->substitutionData([
                'order_id' => $this->order->id,
                'customer_name' => $this->order->customer->name,
                'items' => $this->order->items->map(fn ($item) => [
                    'name' => $item->name,
                    'quantity' => $item->quantity,
                    'price' => $item->formatted_price,
                ])->toArray(),
                'total' => $this->order->formatted_total,
                'shipping_address' => $this->order->shipping_address,
            ]);
    }
}

use Illuminate\Support\Facades\Mail;

// Simple usage — subject comes from the template
Mail::lettr()
    ->to('[email protected]')
    ->sendTemplate('welcome-email', substitutionData: ['name' => 'John']);

// Override the template's subject
Mail::lettr()
    ->to('[email protected]')
    ->sendTemplate('welcome-email', subject: 'Hey John!', substitutionData: ['name' => 'John']);

// With specific template version
Mail::lettr()
    ->to('[email protected]')
    ->sendTemplate('order-confirmation', substitutionData: [
        'order_id' => 123,
        'items' => $items,
    ], version: 2);

// With a custom from address
Mail::lettr()
    ->from('[email protected]', 'Marketing Team')
    ->to('[email protected]')
    ->sendTemplate('promo-campaign', substitutionData: $promoData);

// With CC and BCC
Mail::lettr()
    ->to('[email protected]')
    ->cc('[email protected]')
    ->bcc('[email protected]')
    ->sendTemplate('invoice', substitutionData: $invoiceData);

// With a generated DTO (implements Arrayable)
Mail::lettr()
    ->to('[email protected]')
    ->sendTemplate('welcome-email', substitutionData: new WelcomeEmailData(
        userName: 'John',
        activationUrl: 'https://example.com/activate/abc123',
    ));

// Inline template sending
Mail::lettr()
    ->from('[email protected]', 'Marketing Team')
    ->to('[email protected]')
    ->sendTemplate('promo-campaign', substitutionData: $promoData);

// Regular Mailable sending
Mail::lettr()
    ->from('[email protected]')
    ->to('[email protected]')
    ->send(new OrderConfirmation($order));

class MarketingEmail extends LettrMailable
{
    public function envelope(): Envelope
    {
        return new Envelope(
            from: new Address('[email protected]', 'Marketing Team'),
            subject: 'Special Offer',
        );
    }
}

// Inline template sending
Mail::lettr()
    ->to('[email protected]')
    ->sendTemplate('welcome-email', substitutionData: ['name' => 'John'], customHeaders: [
        'X-Campaign-Id' => 'welcome-2024',
        'X-Entity-Ref' => 'order-123',
    ]);

class WelcomeEmail extends LettrMailable
{
    public function build(): static
    {
        return $this
            ->template('welcome-email')
            ->customHeaders([
                'X-Campaign-Id' => 'welcome-2024',
                'X-Entity-Ref' => 'order-123',
            ]);
    }
}

use Lettr\Exceptions\ApiException;
use Lettr\Exceptions\TransporterException;
use Lettr\Exceptions\ValidationException;
use Lettr\Exceptions\NotFoundException;
use Lettr\Exceptions\UnauthorizedException;
use Lettr\Exceptions\RateLimitException;
use Lettr\Exceptions\QuotaExceededException;

try {
    $response = Lettr::emails()->send($email);
} catch (RateLimitException $e) {
    // Too many requests (429)
    Log::warning("Rate limited, retry after: " . $e->retryAfter . "s");
} catch (QuotaExceededException $e) {
    // Sending quota exceeded
    Log::error("Quota exceeded: " . $e->getMessage());
} catch (ValidationException $e) {
    // Invalid request data (422)
    Log::error("Validation failed: " . $e->getMessage());
} catch (UnauthorizedException $e) {
    // Invalid API key (401)
    Log::error("Authentication failed: " . $e->getMessage());
} catch (NotFoundException $e) {
    // Resource not found (404)
    Log::error("Not found: " . $e->getMessage());
} catch (ApiException $e) {
    // Other API errors
    Log::error("API error ({$e->getCode()}): " . $e->getMessage());
} catch (TransporterException $e) {
    // Network/transport errors
    Log::error("Network error: " . $e->getMessage());
}

return [
    'api_key' => env('LETTR_API_KEY'),

    'templates' => [
        'html_path' => resource_path('templates/lettr'),
        'blade_path' => resource_path('views/emails/lettr'),
        'mailable_path' => app_path('Mail/Lettr'),
        'mailable_namespace' => 'App\\Mail\\Lettr',
        'dto_path' => app_path('Dto/Lettr'),
        'dto_namespace' => 'App\\Dto\\Lettr',
        'enum_path' => app_path('Enums'),
        'enum_namespace' => 'App\\Enums',
        'enum_class' => 'LettrTemplate',
    ],
];

enum LettrTemplate: string
{
    case WelcomeEmail = 'welcome-email';
    case OrderConfirmation = 'order-confirmation';
}

$data = new WelcomeEmailData(userName: 'John', activationUrl: '...');

Mail::lettr()->to('[email protected]')->sendTemplate('welcome-email', substitutionData: $data);
bash
php artisan vendor:publish --tag=lettr-config
bash
php artisan lettr:init
ini
LETTR_API_KEY=your-api-key
ini
MAIL_MAILER=lettr
bash
php artisan lettr:check
bash
php artisan lettr:pull
php artisan lettr:pull --template=welcome-email
php artisan lettr:pull --as-html
php artisan lettr:pull --with-mailables
php artisan lettr:pull --dry-run
bash
php artisan lettr:generate-enum
php artisan lettr:generate-enum --dry-run
bash
php artisan lettr:generate-dtos
php artisan lettr:generate-dtos --template=welcome-email
php artisan lettr:generate-dtos --dry-run
bash
composer analyse