Prerequisites

Before getting started, you’ll need to:
  1. Authorize your sending domain
  2. Create and retrieve your SendLayer API key

Installation

Install the SendLayer PHP SDK using Composer:
composer require sendlayer/sendlayer-php

Usage

After installation, you’re ready to integrate the SDK into your code. The SDK includes modules for sending emails, managing webhooks, and retrieving events.

Sending an Email

Create or edit a .php file. Then import and initialize the client with your API key.
SendEmail.php
<?php
require_once 'vendor/autoload.php';

use SendLayer\SendLayer;

// Initialize the email client with your API key
$sendlayer = new SendLayer('your-api-key');

// Send an email
$response = $sendlayer->Emails->send([
    'from' => 'sender@example.com',
    'to' => 'recipient@example.com',
    'subject' => 'Test Email',
    'text' => 'This is a test email'
]);

Sending HTML Emails

To send HTML emails, include the html parameter when calling send().
SendEmail.php
$response = $sendlayer->Emails->send([
    'from' => 'sender@example.com',
    'to' => 'recipient@example.com',
    'subject' => 'Test Email',
    'html' => "<html><body><p>This is a test email sent with the <a href='https://sendlayer.com'>SendLayer</a> API!</p></body></html>"
]);
You can include the text parameter to provide both plain text and HTML versions of your email.

Sending to Multiple Recipients

You can send emails to multiple recipients and include CC/BCC addresses.
SendEmail.php
$response = $sendlayer->Emails->send([
    'from' => ['email' => 'sender@example.com', 'name' => 'Sender Name'],
    'to' => [
        ['email' => 'recipient1@example.com', 'name' => 'Recipient 1'],
        ['email' => 'recipient2@example.com', 'name' => 'Recipient 2']
    ],
    'subject' => 'Complex Email',
    'html' => '<p>This is a <strong>test email</strong>!</p>',
    'text' => 'This is a test email!',
    'cc' => [['email' => 'cc@example.com', 'name' => 'CC Recipient']],
    'bcc' => [['email' => 'bcc@example.com', 'name' => 'BCC Recipient']],
    'replyTo' => [['email' => 'reply@example.com', 'name' => 'Reply To']]
]);
Each recipient field is an array of objects containing the recipient’s name and email.
There are limits to the number of recipients you can add to a single request. See our rate limiting guide to learn more.

Including Attachments

You can add attachments by including the attachments parameter in the payload.
SendEmail.php
$response = $sendlayer->Emails->send([
    'from' => ['email' => 'sender@example.com', 'name' => 'Sender Name'],
    'to' => [ ['email' => 'recipient1@example.com', 'name' => 'Recipient'] ],
    'subject' => 'Document attached',
    'html' => '<p>See attached file.</p>',
    'attachments' => [
        [
            'path' => '/path/to/document.pdf',
            'type' => 'application/pdf'
        ],
        [
            'path' => 'https://example.com/image.jpg',
            'type' => 'image/jpeg'
        ]
    ]
]);
The maximum email size allowed is 10MB. This includes the message and all attachments.

Email Parameters

Below are the supported parameters for sending emails with the PHP SDK.
ParameterTypeRequiredDescription
tostring or arrayYesEmail address(es) of the recipient(s). Can be a single string or an array of objects with email and name
fromstring or arrayYesEmail address of the sender. Can be a single string or an object with email and name
subjectstringYesSubject line of the email
textstringNoPlain text version of the email content
htmlstringNoHTML version of the email content
ccarrayNoArray of objects for CC recipients
bccarrayNoArray of objects for BCC recipients
replyToarrayNoArray of objects for reply-to addresses
attachmentsarrayNoArray of objects with file path and MIME type
tagsarrayNoArray of strings used to tag emails
headersarrayNoAssociative array of custom headers

Managing Webhooks

With the PHP SDK, you can create webhooks, retrieve them, and delete a specific webhook.

Creating a New Webhook

Initialize the client and call Webhooks->create() with required parameters url and event.
Webhooks.php
<?php
require_once 'vendor/autoload.php';

use SendLayer\SendLayer;

$sendlayer = new SendLayer('your-api-key');

// Create a webhook
$webhook = $sendlayer->Webhooks->create([
    'url' => 'https://your-domain.com/webhook',
    'event' => 'open'
]);
The event parameter accepts the following options:
  • bounce
  • click
  • open
  • unsubscribe
  • complaint
  • delivery
Example success response for a new webhook:
{ "NewWebhookID": 23718 }

Getting All Webhooks

Use Webhooks->get() to view all webhooks you’ve created.
Webhooks.php
$webhooks = $sendlayer->Webhooks->get();
Example response:
{
  "Webhooks": [
    {
      "WebhookID": "23718",
      "CreatedAt": "2025-04-11 09:43:07",
      "UpdatedAt": "2025-04-11 09:43:07",
      "Status": "Enabled",
      "WebhookURL": "http://example.com/webhook",
      "Event": "delivered",
      "LastResponseCode": "0",
      "LastResponseBody": "",
      "LastResponseAt": "0000-00-00 00:00:00",
      "LastResponseTryCounter": "0"
    }
  ]
}

Deleting a Webhook

Use Webhooks->delete() with the numeric webhookId.
Deleting a webhook cannot be undone.
Webhooks.php
$webhookId = 23718;
$sendlayer->Webhooks->delete($webhookId);

Webhooks Parameters

The table below contains details about the supported parameters in the Webhooks module.
ParameterTypeRequiredDescription
urlstringYesThe webhook endpoint URL where events will be sent
eventstringYesThe type of event to listen for. Options: bounce, click, open, unsubscribe, complaint, delivery
webhookIdintegerYesUnique identifier for the webhook (used in delete operation)

Retrieving Email Events

You can view all events connected to your API key.

Getting All Events

Initialize the client and call Events->get() to retrieve events.
The Events->get() method retrieves the top 5 events if no filters are specified.
Events.php
<?php
require_once 'vendor/autoload.php';

use SendLayer\SendLayer;

$sendlayer = new SendLayer('your-api-key');

// Get all events
$events = $sendlayer->Events->get();
Example response:
{
  "totalRecords": 5,
  "events": [
    {
      "Event": "delivered",
      "LoggedAt": 1746340896,
      "LogLevel": "info",
      "Message": {
        "Headers": {
          "MessageId": "06e4491f-fc5a-49cb-bc57-xxxxxx",
          "From": [["", "sender@example.com"]],
          "ReplyTo": [],
          "To": [["", "recipient@example.com"]],
          "Cc": [],
          "Bcc": []
        },
        "Size": 2004,
        "Transport": "api"
      },
      "Recipient": "recipient@example.com",
      "Reason": "Email has been delivered."
    }
  ]
}

Filtering Events

You can filter events by date range, event type, message ID, and pagination options.
Events.php
// Filter events for the last 4 hours
$events = $sendlayer->Events->get([
    'startDate' => new DateTime('-4 hours'),
    'endDate' => new DateTime('now'),
    'event' => 'opened'
]);

Events Parameters

The table below lists available parameters in the Events module.
ParameterTypeRequiredDescription
startDateDateTime or intNoStart date for filtering events (Unix timestamp or DateTime)
endDateDateTime or intNoEnd date for filtering events (Unix timestamp or DateTime)
eventstringNoFilter by event type. Supported: accepted, rejected, delivered, opened, clicked, unsubscribed, complained, failed
messageIdstringNoFilter by the email MessageId
startFromintegerNoStarting position for pagination
retrieveCountintegerNoNumber of event records to retrieve (defaults to 5)

Error Handling

Use try/catch blocks to handle SDK errors. The SDK provides specific exception types for different failure scenarios.
SendEmail.php
<?php
require_once 'vendor/autoload.php';

use SendLayer\Exceptions\SendLayerAPIException;
use SendLayer\Exceptions\SendLayerException;

try {
    $response = $sendlayer->Emails->send([ /* ... */ ]);
} catch (SendLayerAPIException $e) {
    // API-specific error with status code and response data
    echo 'API error: ' . $e->getStatusCode() . ' - ' . $e->getMessage();
} catch (SendLayerException $e) {
    // Other SDK errors (validation, auth, network, etc.)
    echo 'Error: ' . $e->getMessage();
}
Here is an example error response:
Error: Invalid event name - 'opened' is not a valid event name

Exception Types

  • SendLayerException: Base exception for all SendLayer errors
  • SendLayerAuthenticationException: Invalid API key or authentication issues
  • SendLayerValidationException: Invalid parameters or validation errors
  • SendLayerAPIException: API-specific errors with status code and response data

More Examples

SendLayer PHP SDK

View more details and examples on GitHub.