Documentation

PHP SDK

PHP 8.1+
Composer

Send emails with PHP using the official Laneful PHP SDK. Built for modern PHP applications with comprehensive features and type safety.

Full Feature Support

Templates, attachments, tracking, webhooks

Type Safe

Built-in validation & error handling

Modern PHP

PHP 8.1+ with named parameters

Prerequisites

To get the most out of this guide, you'll need:

  • • PHP 8.1 or higher
  • • Composer 2.0+
  • • A Laneful account with API key
  • • Verified domain for sending emails

Installation

Composer

Run this command in your project directory. This page describes version 1.2.0:

composer require lanefulhq/laneful-php:^1.2

Quick Start

Send your first email in minutes:

Send Simple Text Email

<?php

require_once 'vendor/autoload.php';

use Laneful\LanefulClient;
use Laneful\Models\Email;
use Laneful\Models\Address;
use Laneful\Exceptions\{ApiException, HttpException};

// Create client
$client = new LanefulClient(
    baseUrl: 'https://your-endpoint.z1.send.laneful.net',
    authToken: 'your-auth-token'
);

try {
    // Create email (invalid input throws \InvalidArgumentException)
    $email = new Email(
        from: new Address('sender@example.com', 'Your Name'),
        to: [new Address('recipient@example.com', 'Recipient Name')],
        subject: 'Hello from Laneful!',
        textContent: 'This is a simple test email sent using the Laneful PHP SDK.'
    );

    // Send email
    $response = $client->sendEmail($email);
    echo "✓ Email sent successfully!\n";
    echo "Response: " . json_encode($response) . "\n";
} catch (\InvalidArgumentException $e) {
    echo "✗ Validation error: " . $e->getMessage() . "\n";
} catch (ApiException $e) {
    echo "✗ API error: " . $e->getMessage() . "\n";
    echo "Status code: " . $e->getCode() . "\n";
} catch (HttpException $e) {
    echo "✗ HTTP error: " . $e->getMessage() . "\n";
} catch (Exception $e) {
    echo "✗ Unexpected error: " . $e->getMessage() . "\n";
}

Replace https://your-endpoint.z1.send.laneful.net with your organization's own HTTP API endpoint and your-auth-token with a private API key, both available in the dashboard under Workspaces → Workspace Settings → API Keys (see Sending Email). The API is HTTPS-only.

Examples

Common use cases and patterns:

HTML Email with Tracking

use Laneful\Models\TrackingSettings;

// Create tracking settings
$tracking = new TrackingSettings(opens: true, clicks: true, unsubscribes: true);

$email = new Email(
    from: new Address('sender@example.com', 'Your Name'),
    to: [new Address('recipient@example.com', 'Recipient Name')],
    subject: 'HTML Email with Tracking',
    htmlContent: '<h1>Welcome!</h1><p>This is an <strong>HTML email</strong> with tracking enabled.</p>',
    textContent: 'Welcome! This is an HTML email with tracking enabled.',
    tracking: $tracking,
    tag: 'welcome-email'
);

$response = $client->sendEmail($email);

Template Email

use Laneful\Models\TrackingSettings;

// subject is required by the API, also with a template
$email = new Email(
    from: new Address('sender@example.com'),
    to: [new Address('user@example.com')],
    subject: 'Welcome to Acme Corporation',
    templateId: 'welcome-template',
    templateData: [
        'name' => 'John Doe',
        'company' => 'Acme Corporation',
        'activation_link' => 'https://example.com/activate'
    ],
    tracking: new TrackingSettings(opens: true, clicks: true)
);

$response = $client->sendEmail($email);

Email with Attachments

use Laneful\Models\Attachment;
use Laneful\Models\TrackingSettings;

// Create attachment from file
$attachment = Attachment::fromFile('/path/to/document.pdf');

$email = new Email(
    from: new Address('sender@example.com'),
    to: [new Address('user@example.com')],
    subject: 'Document Attached',
    textContent: 'Please find the document attached.',
    attachments: [$attachment],
    tracking: new TrackingSettings(opens: true, clicks: true)
);

$response = $client->sendEmail($email);

Multiple Recipients with Reply-To

use Laneful\Models\TrackingSettings;

$email = new Email(
    from: new Address('sender@example.com', 'Your Name'),
    to: [
        new Address('user1@example.com', 'User One'),
        new Address('user2@example.com', 'User Two')
    ],
    cc: [new Address('cc@example.com', 'CC Recipient')],
    bcc: [new Address('bcc@example.com', 'BCC Recipient')],
    replyTo: new Address('reply@example.com', 'Reply To'),
    subject: 'Email to Multiple Recipients',
    textContent: 'This email is being sent to multiple recipients.',
    tracking: new TrackingSettings(opens: true, clicks: true)
);

$response = $client->sendEmail($email);

Scheduled Email

use Laneful\Models\TrackingSettings;

// Schedule for 24 hours from now
$sendTime = time() + (24 * 60 * 60);

$email = new Email(
    from: new Address('sender@example.com'),
    to: [new Address('user@example.com')],
    subject: 'Scheduled Email',
    textContent: 'This email was scheduled.',
    sendTime: $sendTime,
    tracking: new TrackingSettings(opens: true, clicks: true)
);

$response = $client->sendEmail($email);

Batch Email Sending

$emails = [
    new Email(
        from: new Address('sender@example.com'),
        to: [new Address('user1@example.com')],
        subject: 'Email 1',
        textContent: 'First email content.'
    ),
    new Email(
        from: new Address('sender@example.com'),
        to: [new Address('user2@example.com')],
        subject: 'Email 2',
        textContent: 'Second email content.'
    )
];

$response = $client->sendEmails($emails);

Webhook Handler Example

use Laneful\Webhooks\WebhookVerifier;

// Complete webhook handler implementation
class WebhookController {
    private string $webhookSecret;
    
    public function __construct(string $webhookSecret) {
        $this->webhookSecret = $webhookSecret;
    }
    
    public function handleWebhook(): void {
        try {
            // Extract signature from headers
            $signature = WebhookVerifier::extractSignatureFromHeaders($_SERVER);
            if (!$signature) {
                $this->respond(401, 'Missing signature');
                return;
            }
            
            // Get raw payload
            $payload = file_get_contents('php://input');
            
            // Verify signature
            if (!WebhookVerifier::verifySignature($this->webhookSecret, $payload, $signature)) {
                $this->respond(401, 'Invalid signature');
                return;
            }
            
            // Parse and validate payload
            $webhookData = WebhookVerifier::parseWebhookPayload($payload);
            
            // Process events
            foreach ($webhookData['events'] as $event) {
                $eventType = $event['event'];
                $email = $event['email'];
                
                switch ($eventType) {
                    case 'request':
                        error_log("Email accepted for: " . $email);
                        break;
                    case 'delivery':
                        error_log("Email delivered to: " . $email);
                        break;
                    case 'open':
                        error_log("Email opened by: " . $email);
                        break;
                    case 'click':
                        $url = $event['url'] ?? 'Unknown URL';
                        error_log("Link clicked by " . $email . ": " . $url);
                        break;
                    case 'bounce':
                        $isHard = $event['is_hard'] ?? false;
                        error_log("Email bounced (" . ($isHard ? "hard" : "soft") . ") for: " . $email);
                        break;
                }
            }
            
            $this->respond(200, 'Webhook processed successfully');
            
        } catch (\InvalidArgumentException $e) {
            $this->respond(400, 'Invalid payload: ' . $e->getMessage());
        } catch (Exception $e) {
            $this->respond(500, 'Processing error: ' . $e->getMessage());
        }
    }
    
    private function respond(int $status, string $message): void {
        http_response_code($status);
        header('Content-Type: application/json');
        echo json_encode(['status' => $status, 'message' => $message]);
    }
}

$controller = new WebhookController((string) getenv('LANEFUL_WEBHOOK_SECRET'));
$controller->handleWebhook();

API Reference

LanefulClient

Constructor

  • • LanefulClient(string $baseUrl, string $authToken, ?\GuzzleHttp\Client $httpClient = null, int $timeout = 30) - $timeout is in seconds and applies to every request. Pass it by name: new LanefulClient(baseUrl: $baseUrl, authToken: $authToken, timeout: 60). Validates its arguments up front and throws ValidationException if $baseUrl or $authToken is empty.
  • • Create a custom $httpClient with 'http_errors' => false so API error responses arrive as ApiException (otherwise they arrive as HttpException).

Methods

  • • array sendEmail(Email $email, ?MailSettings $settings = null) - Send single email; returns the decoded JSON response
  • • array sendEmails(array $emails, ?MailSettings $settings = null) - Send multiple emails in one request; returns the decoded JSON response

Email

Required Fields

  • • Address $from - Sender address
  • • string|null $subject - Email subject. Always provide it, also when $templateId is set: the API requires a subject, and the SDK leaves that check to the API
  • • At least one recipient in $to, $cc or $bcc, and $textContent, $htmlContent or $templateId. The constructor checks both for you and throws \InvalidArgumentException if either is missing

Optional Fields

  • • Address[] $to - Recipient addresses
  • • Address[] $cc - CC recipient addresses
  • • Address[] $bcc - BCC recipient addresses
  • • Address|null $replyTo - Reply-to address
  • • Address|null $fromHeader - Address for the visible From header, if it should differ from $from
  • • string|null $textContent - Plain text content
  • • string|null $htmlContent - HTML content
  • • string|null $templateId - Template ID
  • • array|null $templateData - Template data
  • • Attachment[] $attachments - File attachments
  • • array|null $headers - Custom email headers as key-value pairs. Set From, To, Cc, Bcc, Reply-To and Subject with their own parameters and let Laneful generate the Message-ID; header entries for these are ignored (see Sending Email)
  • • int|null $sendTime - Scheduled send time
  • • array|null $webhookData - Your own string key-value pairs, returned unchanged as metadata on every webhook event for this email (max 20 keys, keys up to 50 bytes, values up to 100 bytes in UTF-8)
  • • TrackingSettings|null $tracking - Email tracking configuration
  • • string|null $tag - Email tag for categorization

Utility Classes

  • • Address(string $email, ?string $name = null) - Email address with optional name
  • • Attachment::fromFile(string $filePath, ?string $fileName = null) - Create attachment from file (read and Base64-encoded for you)
  • • Attachment(string $contentType, ?string $fileName = null, ?string $content = null, ?string $inlineId = null) - Create attachment from data; $content must be Base64-encoded, $inlineId is for inline images
  • • TrackingSettings(?bool $opens = null, ?bool $clicks = null, ?bool $unsubscribes = null, ?int $unsubscribeGroupId = null, ?string $unsubscribeGroupName = null) - Email tracking configuration and unsubscribe group (by ID or name). Set only what you want to change: null values are left out of the request, so the API defaults apply (opens, clicks and unsubscribes default to true)
  • • MailSettings(?bool $sandboxMode = null, ?bool $returnMessageIds = null, ?string $idempotencyKey = null) - Request-level settings for sendEmail() and sendEmails(). With returnMessageIds: true the response includes message_ids, each matching the message_id on that email's webhook events (every email must then have exactly one recipient). idempotencyKey (1 to 36 bytes, 1.2.0 and later) prevents duplicate sends, see Error Handling. See Sending Email.

WebhookVerifier

Signature Verification

  • • bool verifySignature(string $secret, string $payload, string $signature) - Verifies webhook signature (supports sha256= prefix). Returns false if the secret, payload or signature is empty
  • • string generateSignature(string $secret, string $payload) - Generates signature for payload
  • • string generateSignature(string $secret, string $payload, bool $includePrefix) - Generates signature with optional prefix

Payload Processing

  • • array parseWebhookPayload(string $payload) - Parse and validate webhook payload structure. Throws \InvalidArgumentException for the whole payload if any event is invalid. From 1.2.0, events of unknown types are kept and the empty lane_id of request events is accepted; earlier versions reject the whole payload
  • • string getSignatureHeaderName() - Get the correct header name for webhook signatures
  • • ?string extractSignatureFromHeaders(array $headers) - Extract signature from HTTP headers. Pass $_SERVER; keys are matched exactly (HTTP_X_WEBHOOK_SIGNATURE, X_WEBHOOK_SIGNATURE or x-webhook-signature)

parseWebhookPayload() result

  • • bool isBatch - True if the body is a JSON array (batch mode), even with one event
  • • array events - The events as associative arrays with every field Laneful sent, including id and metadata

Organization API Methods

  • • Unsubscribe groups: listUnsubscribeGroups(int $workspaceId, ...), createUnsubscribeGroup(int $workspaceId, ...), updateUnsubscribeGroup(int $workspaceId, int $unsubscribeGroupId, ...)
  • • Domains: listDomains(int $workspaceId, ...), getDomain(int $workspaceId, string $domain), createDomain(int $workspaceId, ...), updateDomain(int $workspaceId, string $domain, ...), verifyDomain(int $workspaceId, string $domain), deleteDomain(int $workspaceId, string $domain)
  • • Analytics: listDomainSpamRatioRadar, listGooglePostmasterSpamReports, listSndsReports

These methods call the Organization API, so create a separate client with base URL https://api.laneful.net and an Organization API key (see Organization API). Domain and unsubscribe group methods are scoped to a workspace and take int $workspaceId as their first argument (the API routes them under /v1/workspaces/{workspace_id}/...).

Error Handling

Comprehensive error handling with specific exception types:

use Laneful\Exceptions\{ApiException, HttpException};

try {
    $email = new Email(
        from: new Address('sender@example.com'),
        to: [new Address('user@example.com')],
        subject: 'Hello from Laneful!',
        textContent: 'This is a test email.'
    );

    $response = $client->sendEmail($email);
    echo "✓ Email sent successfully!\n";
    echo "Response: " . json_encode($response) . "\n";
} catch (\InvalidArgumentException $e) {
    // Invalid input data (thrown by the Email, Address and Attachment constructors)
    echo "✗ Validation error: " . $e->getMessage() . "\n";
    echo "Please check your email configuration\n";
} catch (ApiException $e) {
    // API returned an error
    echo "✗ API error: " . $e->getMessage() . "\n";
    echo "  Status code: " . $e->getCode() . "\n";
    echo "Please check your API credentials and endpoint\n";
} catch (HttpException $e) {
    // Network or HTTP-level error
    echo "✗ HTTP error: " . $e->getMessage() . "\n";
    echo "  Status code: " . $e->getCode() . "\n";
    echo "Please check your network connection and endpoint URL\n";
} catch (Exception $e) {
    // Other unexpected errors
    echo "✗ Unexpected error: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString() . "\n";
}

Exception Types

  • • \InvalidArgumentException - Invalid input to the Email, Address or Attachment constructors. It's PHP's built-in exception rather than a LanefulException, so catch it separately
  • • ValidationException - Empty base URL or API key, or an empty or invalid sendEmails() array
  • • ApiException - API returns error response
    Methods: getCode() (HTTP status), getMessage()
  • • HttpException - HTTP communication fails (network error, timeout, 404 from a wrong base URL, or a non-JSON response)
    Methods: getCode()
  • • LanefulException - Base exception class

Best Practices

  • • Always wrap API calls in try-catch
  • • Handle specific exception types first
  • • Log errors with context information
  • • The SDK leaves retries to you. A send that timed out may already have been accepted, so when you retry it, reuse the same idempotencyKey (see below)

Duplicate Send Protection

Pass an idempotencyKey (1 to 36 bytes, see Sending Email) and reuse it when you retry a send, for example after a timeout:

use Laneful\Models\MailSettings;

$response = $client->sendEmail(
    $email,
    new MailSettings(idempotencyKey: "order-{$orderId}-receipt")
);

Laneful remembers a key per organization for one hour. A repeated request with the same key returns status accepted with no message IDs and sends nothing, even if the emails differ, so use a new key for every distinct send. Detection is best effort. A request that fails with HTTP 500 doesn't keep its key, so a retry with it is processed as a new request: before resending after a 500, check your webhook events (a request event means Laneful accepted the email). Sandbox mode requests aren't deduplicated. A key outside 1 to 36 bytes throws Laneful\Exceptions\ValidationException. Requires 1.2.0 or later.

Webhook Handling

Comprehensive webhook handling with signature verification, payload parsing, and validation:

  • • Verify the raw body (php://input) before parsing it: Laneful signs it with HMAC-SHA256 using your webhook secret and sends the hex digest, without a prefix, in the X-Webhook-Signature header. verifySignature() also accepts a sha256= prefix and returns false without a secret.
  • • Return a 2xx within 30 seconds to acknowledge each webhook call; Laneful automatically retries any other outcome for up to 24 hours. Reserve 401 for a bad signature and 400 for a payload that can't be parsed, and answer 5xx when your handler fails.
  • • Use version 1.1.0 or later: it supports every event type Laneful sends, including request (earlier versions reject payloads that contain one). From 1.2.0, parseWebhookPayload() also keeps events of unknown types; 1.1 rejects the whole payload, batch included, if any event type is unknown.
  • • Parsed events keep every field Laneful sends: use id (unique per event and unchanged on retries) to skip duplicates, and metadata to read back the email's webhookData. See Webhooks for all fields.
  • • Use the default Laneful webhook format with parseWebhookPayload(); it reads that format rather than the Mailgun or SendGrid formats.

Basic Signature Verification

use Laneful\Webhooks\WebhookVerifier;

// In your webhook handler
$payload = file_get_contents('php://input'); // Get the raw request body
$signature = WebhookVerifier::extractSignatureFromHeaders($_SERVER);
$secret = (string) getenv('LANEFUL_WEBHOOK_SECRET');

if ($signature && WebhookVerifier::verifySignature($secret, $payload, $signature)) {
    try {
        $webhookData = WebhookVerifier::parseWebhookPayload($payload);
        // Handle webhook events
    } catch (\InvalidArgumentException $e) {
        http_response_code(400);
        echo "Invalid webhook payload";
    }
} else {
    // Invalid signature
    http_response_code(401);
    echo "Invalid webhook signature";
}

Advanced Webhook Processing

use Laneful\Webhooks\WebhookVerifier;

// Complete webhook verification and processing workflow
$webhookSecret = (string) getenv('LANEFUL_WEBHOOK_SECRET');

// Step 1: Get raw payload
$payload = file_get_contents('php://input');

// Step 2: Extract signature from headers (X-Webhook-Signature)
$signature = WebhookVerifier::extractSignatureFromHeaders($_SERVER);

// Step 3: Verify signature over the raw payload
if (!$signature || !WebhookVerifier::verifySignature($webhookSecret, $payload, $signature)) {
    http_response_code(401);
    echo "Invalid webhook signature";
    exit;
}

// Step 4: Parse and validate payload structure
try {
    $webhookData = WebhookVerifier::parseWebhookPayload($payload);
} catch (\InvalidArgumentException $e) {
    http_response_code(400);
    echo "Invalid payload: " . $e->getMessage();
    exit;
}

// Step 5: Process events (handles both batch and single event formats).
// The handle...Event() functions are yours; if one fails, answer 5xx so Laneful retries.
try {
    foreach ($webhookData['events'] as $event) {
        switch ($event['event']) {
            case 'request':
                handleRequestEvent($event);
                break;
            case 'delivery':
                handleDeliveryEvent($event);
                break;
            case 'open':
                handleOpenEvent($event);
                break;
            case 'click':
                handleClickEvent($event);
                break;
            case 'bounce':
                handleBounceEvent($event);
                break;
            case 'drop':
                handleDropEvent($event);
                break;
            case 'spam_complaint':
                handleSpamComplaintEvent($event);
                break;
            case 'unsubscribe':
                handleUnsubscribeEvent($event);
                break;
        }
    }
} catch (\Throwable $e) {
    http_response_code(500);
    echo "Processing error: " . $e->getMessage();
    exit;
}

http_response_code(200);
echo "OK";

Batch Mode Support

// $payload: the raw request body, after its signature has been verified
$webhookData = WebhookVerifier::parseWebhookPayload($payload);

if ($webhookData['isBatch']) {
    // Batch mode: the body is a JSON array of events
    echo "Processing " . count($webhookData['events']) . " events in batch";
} else {
    // Processing single event
    echo "Processing single event";
}

// Process all events
foreach ($webhookData['events'] as $event) {
    processEvent($event);
}

Supported Webhook Events

Delivery Events

  • • request - Email accepted and queued for delivery
  • • delivery - Email delivered successfully
  • • bounce - Email bounced (hard or soft)
  • • drop - Email dropped (spam, invalid, etc.)
  • • spam_complaint - Recipient marked email as spam

Engagement Events

  • • open - Email opened by recipient
  • • click - Link clicked in email
  • • unsubscribe - Recipient unsubscribed

Webhook Features

Security

  • • HMAC-SHA256 signature verification
  • • Bare hex signatures, as Laneful sends them (a sha256= prefix is also accepted)
  • • Constant-time comparison (timing attack protection)
  • • Multiple header format support

Validation

  • • JSON payload structure validation
  • • Required field validation
  • • Email format validation

Ready to Get Started?

Start sending emails with PHP in minutes. Check out the examples and integrate with your application.