PHP code example of letmesendemail / letmesendemail-php

1. Go to this page and download the library: Download letmesendemail/letmesendemail-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/ */

    

letmesendemail / letmesendemail-php example snippets


use LetMeSendEmail\LetMeSendEmail;

$apiKey = getenv('LETMESENDEMAIL_API_KEY');
if ($apiKey === false || $apiKey === '') {
    throw new \RuntimeException('LETMESENDEMAIL_API_KEY is not set.');
}

$client = new LetMeSendEmail(apiKey: $apiKey);

$email = $client->emails()->send(
    from: 'Acme <[email protected]>',
    to: ['[email protected]'],
    subject: 'Welcome',
    html: '<p>Hello from letmesend.email</p>',
);

echo $email->getId(); // "01kvv5a6xk9qd6y2egeae8w76e"

use LetMeSendEmail\LetMeSendEmail;
use LetMeSendEmail\Configuration;

// Simple setup with just an API key:
$client = new LetMeSendEmail(apiKey: 'lms_live_...');

// With custom configuration:
$config = new Configuration(
    apiKey: 'lms_live_...',
    baseUrl: 'https://letmesend.email/api/v1',  // default
    timeout: 60,                                  // default: 30 seconds
);

$client = new LetMeSendEmail(configuration: $config);

$email = $client->emails()->send(
    from: 'Acme <[email protected]>',
    to: ['[email protected]', 'Jane <[email protected]>'],
    subject: 'Welcome to letmesend.email',
    html: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
    text: 'Welcome! Thanks for signing up.',
    type: 'transactional', // or 'broadcast'
    eventName: 'user.created',
    replyTo: ['[email protected]'],
    cc: ['[email protected]'],
    bcc: ['[email protected]'],
    headers: ['X-Custom-Header' => 'value'],
    attachments: [
        [
            'name' => 'report.pdf',
            'mime' => 'application/pdf',
            'path' => 'https://storage.example.com/report.pdf',
        ],
    ],
);

echo $email->getId();         // "01kvv5a6xk9qd6y2egeae8w76e"
echo $email->getStatus();     // "pending_scan" or "accepted"
print_r($email->getEmails()); // list of all recipient addresses

use LetMeSendEmail\Requests\Attachment;

// From a URL (external file)
$attachment = Attachment::fromPath(
    name: 'report.pdf',
    path: 'https://example.com/report.pdf',
    contentId: 'optional-cid',
    contentDisposition: 'attachment', // or 'inline'
);

// From base64 content
$attachment = Attachment::fromContent(
    name: 'data.txt',
    content: base64_encode('Hello World'),
    contentId: 'optional-cid',
    contentDisposition: 'inline',
);

$email = $client->emails()->send(
    from: 'Acme <[email protected]>',
    to: ['[email protected]'],
    subject: 'With attachment',
    html: '<p>See attached</p>',
    attachments: [$attachment],
);

// Raw arrays:
$email = $client->emails()->sendWithTemplate(
    from: 'Acme <[email protected]>',
    to: ['[email protected]'],
    templateId: '01ARZ3NDEKTSV4RRFFQ69G5FAV',
    subject: 'Your order confirmation',
    templateVariables: [
        ['key' => 'USER_NAME', 'type' => 'string', 'value' => 'John'],
        ['key' => 'ORDER_NUMBER', 'type' => 'number', 'value' => 12345],
    ],
);

use LetMeSendEmail\Requests\TemplateVariable;

$email = $client->emails()->sendWithTemplate(
    from: 'Acme <[email protected]>',
    to: ['[email protected]'],
    templateId: '01ARZ3NDEKTSV4RRFFQ69G5FAV',
    templateVariables: [
        new TemplateVariable('USER_NAME', 'string', 'John'),
        new TemplateVariable('ORDER_NUMBER', 'number', 12345),
    ],
);

$email = $client->emails()->send(
    from: 'Acme <[email protected]>',
    to: ['[email protected]'],
    subject: 'Your invoice',
    html: '<p>Invoice attached</p>',
    idempotencyKey: 'my-unique-key-abc123',
);

if ($email->isDuplicate()) {
    // This send was a duplicate — the original send was not re-attempted.
}

$result = $client->emails()->verify('[email protected]');

echo $result->getStatus();     // "valid", "invalid", or "risky"
echo $result->getScore();      // 0-100
echo $result->hasMailbox();    // true
echo $result->isDisposable();  // false
echo $result->hasValidSyntax(); // true

// First page
$list = $client->emails()->list(perPage: 20);

foreach ($list->items() as $email) {
    echo $email->getId() . ' - ' . ($email->getSubject() ?? '(no subject)') . PHP_EOL;
}

// Pagination info
$pagination = $list->pagination();
echo $pagination->hasMore(); // true
echo $pagination->getTotal(); // 100

// Next page using the last item's ID
if ($list->pagination()->hasMore() && count($list->items()) > 0) {
    $items = $list->items();
    $lastId = $items[count($items) - 1]->getId();
    $nextPage = $client->emails()->list(perPage: 20, after: $lastId);
}

// Previous page using the first item's ID (from a page other than the first)
if (count($list->items()) > 0) {
    $items = $list->items();
    $firstId = $items[0]->getId();
    $prevPage = $client->emails()->list(perPage: 20, before: $firstId);
}

$email = $client->emails()->get('01kvv5dv472evp42a60sy4p7zx');

echo $email->getStatus();           // "sent", "queued", etc.
echo $email->getSubject();          // email subject
echo $email->getRecipientsCount();  // 1
echo $email->getAttachmentsCount(); // 0

// Typed recipient objects
foreach ($email->getRecipients() as $recipient) {
    echo $recipient->getEmailAddress(); // "[email protected]"
    echo $recipient->getStatus();       // "queued", "delivered", "bounced"
    echo $recipient->getOpenCount();    // opens count
    echo $recipient->getClickCount();   // clicks count
}

// Typed attachment objects
foreach ($email->getAttachments() as $attachment) {
    echo $attachment->getName();          // "I9wJnL1QeUOKnsgE.png"
    echo $attachment->getMime();          // "image/png"
    echo $attachment->getSize();          // 16174079
    echo $attachment->getDownloadUrl();   // signed download URL
}

$list = $client->domains()->list(perPage: 20);

foreach ($list->items() as $domain) {
    echo $domain->getId() . ' - ' . $domain->getDomainName() . ' (' . $domain->getStatus() . ')' . PHP_EOL;
}

$pagination = $list->pagination();
echo $pagination->hasMore(); // true/false

$domain = $client->domains()->get('01kvv5th65xzkwxe5avmdqbn4a');

echo $domain->getDomainName(); // "mpxlubowitz.com"
echo $domain->getStatus();     // "verified" or "pending"

$result = $client->domains()->verify('mpxlubowitz.com');

echo $result->getStatus(); // "verified"

$contact = $client->contacts()->create(
    email: '[email protected]',
    firstName: 'John',
    lastName: 'Doe',
    phone: '11231231234',
    categories: ['01kvtsch6f6e7hz543mjyjnqsp'],
);

echo $contact->getId(); // "01kvtsch6t80qpx3ncfea2r5a3"
echo $contact->getFirstName(); // "John"

$list = $client->contacts()->list(perPage: 10);

foreach ($list->items() as $contact) {
    echo $contact->getEmail() . ' - ' . $contact->getFirstName() . PHP_EOL;
}

$contact = $client->contacts()->get('01kvtsch80sxnzw8cggwhh22x2');

echo $contact->getEmail();     // "[email protected]"
echo $contact->getFirstName(); // "Jalen"

$result = $client->contacts()->update(
    id: '01kvtsch98rxyxwaxwx2fbpsbp',
    firstName: 'John',
    lastName: 'Doe',
    syncCategories: false,
);

echo $result->getId(); // "01kvtsch98rxyxwaxwx2fbpsbp"

$result = $client->contacts()->delete('01kvtscham9bjdwftnxxa8at1k');

echo $result->getStatus(); // "success"

$category = $client->contactCategories()->create(name: 'New Name');

echo $category->getId();   // "01kvtkm3x5tpyhyw7xcnqf32rj"
echo $category->getName(); // "New Name"
echo $category->getSlug(); // "new-name"

$list = $client->contactCategories()->list(perPage: 20);

foreach ($list->items() as $category) {
    echo $category->getName() . ' (' . $category->getSlug() . ')' . PHP_EOL;
}

$category = $client->contactCategories()->get('01kvtr2b9ztdvggdbrcjmm45nj');

echo $category->getName(); // "Category Name"

$category = $client->contactCategories()->update(
    id: '01kvtkq34gc5zqbxpyw90q4sk6',
    name: 'New Name',
    slug: 'new-name',
);

echo $category->getSlug(); // "new-name"

$result = $client->contactCategories()->delete('01kvtmr3evcs2brxp2vcztd102');

echo $result->getStatus(); // "success"

$topic = $client->emailTopics()->create(
    name: 'Product Updates',
    slug: 'product-updates',
    description: 'Emails for product updates',
    autoSubscribe: true,
    public: true,
    domainId: '01kvtsgfavkx5609jd3j2t6jr1', // optional
);

echo $topic->getId();   // "01kvtsgfb2rp5g1y3xdsrnk6n4"
echo $topic->getName(); // "Product Updates"

$list = $client->emailTopics()->list(perPage: 20);

foreach ($list->items() as $topic) {
    echo $topic->getName() . ' - ' . ($topic->getDescription() ?? '(no description)') . PHP_EOL;
}

$topic = $client->emailTopics()->get('01kvtsgf9e96nnj98nxsac751r');

echo $topic->getName(); // "Billing Notifications"
echo $topic->isAutoSubscribe(); // false

$topic = $client->emailTopics()->update(
    id: '01kvtsgfcbte0npnqkj8kep642',
    name: 'New Name',
    description: 'Updated description',
    public: true,
);

echo $topic->getName(); // "New Name"

$result = $client->emailTopics()->delete('01kvtsgfdq4xw54vcvqw0ae68n');

echo $result->getStatus();  // "success"
echo $result->getMessage(); // "Email category deleted"

use LetMeSendEmail\Exceptions\ValidationError;
use LetMeSendEmail\Exceptions\AuthenticationError;
use LetMeSendEmail\Exceptions\RateLimitError;
use LetMeSendEmail\Exceptions\ApiException;

try {
    $client->emails()->send(/* ... */);
} catch (ValidationError $e) {
    echo $e->getMessage();
    print_r($e->getValidationErrors()); // field-level errors
} catch (AuthenticationError $e) {
    echo 'Check your API key.';
} catch (RateLimitError $e) {
    echo 'Retry after ' . $e->getRetryAfter() . ' seconds.';
} catch (ApiException $e) {
    echo 'HTTP ' . $e->getHttpStatus() . ': ' . $e->getMessage();
}

$list = $client->emails()->list(perPage: 10);

// Items on this page
$emails = $list->items();

// Pagination metadata
$pag = $list->pagination();
$pag->hasMore();   // bool
$pag->getTotal();  // int
$pag->getPerPage(); // int
$pag->getFetched(); // int

// Next page: use the last item's ID
if ($list->pagination()->hasMore() && count($list->items()) > 0) {
    $items = $list->items();
    $nextList = $client->emails()->list(after: $items[count($items) - 1]->getId());
}

// Previous page: use the first item's ID (from a page other than the first)
if (count($list->items()) > 0) {
    $items = $list->items();
    $prevList = $client->emails()->list(before: $items[0]->getId());
}

$config = new Configuration(
    apiKey: 'lms_live_...',
    retries: 3,
);

$client = new LetMeSendEmail(configuration: $config);

use LetMeSendEmail\Support\WebhookSignature;
use LetMeSendEmail\Exceptions\WebhookVerificationException;
use LetMeSendEmail\Exceptions\WebhookSigningException;

$payload = file_get_contents('php://input');
if ($payload === false) {
    http_response_code(400);
    echo 'Failed to read request body.';
    exit;
}

$headers = getallheaders();
if (!is_array($headers)) {
    $headers = [];
}

$secret = getenv('LETMESENDEMAIL_WEBHOOK_SECRET');
if ($secret === false || $secret === '') {
    http_response_code(500);
    echo 'Webhook secret is not configured.';
    exit;
}

try {
    $event = WebhookSignature::verify(
        payload: $payload,
        headers: $headers,
        secret: $secret,
        tolerance: 300,
    );

    // $event contains the verified payload as an associative array
} catch (WebhookVerificationException $e) {
    http_response_code(400);
    echo 'Webhook verification failed: ' . $e->getMessage();
} catch (WebhookSigningException $e) {
    http_response_code(500);
    echo 'Webhook configuration error: ' . $e->getMessage();
}
bash
composer