PHP
Official Unsent PHP SDK for sending emails and managing contacts.
This guide shows how to install and use the official souravsspace/unsent PHP SDK.
Installation
Install the SDK via Composer. Run the following command in your project directory:
composer require souravsspace/unsentInitialize
To start using the SDK, you need to initialize the Unsent client. You can pass your API key directly to the constructor, or set it as an environment variable UNSENT_API_KEY.
<?php
require 'vendor/autoload.php';
use Souravsspace\Unsent\Unsent;
// Option 1: Pass API key directly
$client = new Unsent('un_xxx');
// Option 2: Use environment variable UNSENT_API_KEY
// $client = new Unsent();Send an email
Now you can send an email. The SDK methods return a tuple [$data, $error]. You should always check if $error is present to handle any issues.
Here is an example of sending a simple HTML email:
<?php
use Souravsspace\Unsent\Unsent;
$client = new Unsent('un_xxx');
[$data, $error] = $client->emails->send([
'to' => 'user@example.com',
'from' => 'no-reply@yourdomain.com',
'subject' => 'Welcome',
'html' => '<strong>Hello!</strong>',
'headers' => ['X-Campaign' => 'welcome'],
]);
if ($error) {
echo "Error: " . $error['message'];
} else {
echo "Email sent! ID: " . $data['emailId'];
}Note
Unsent forwards your custom headers to SES. Only the X-Unsent-Email-ID and References headers are managed automatically by Unsent.
Attachments and scheduling
You can also send emails with attachments and schedule them for later delivery.
- Attachments: Provide an array of attachments, where each attachment has a
filenameandcontent(Base64 encoded string). - Scheduling: Use the
scheduledAtfield with aDateTimeobject or an ISO 8601 string.
<?php
use DateTime;
[$data, $error] = $client->emails->send([
'to' => ['user1@example.com', 'user2@example.com'],
'from' => 'no-reply@yourdomain.com',
'subject' => 'Report',
'text' => 'See attached.',
'attachments' => [
[
'filename' => 'report.txt',
'content' => 'SGVsbG8gd29ybGQ=', // Content must be Base64 encoded
],
],
'scheduledAt' => new DateTime('+10 minutes'), // Schedule for 10 minutes from now
]);Batch send
To send multiple emails efficiently in a single request, use the batch method.
<?php
$emails = [
[
'to' => 'a@example.com',
'from' => 'no-reply@yourdomain.com',
'subject' => 'A',
'html' => '<p>A</p>',
],
[
'to' => 'b@example.com',
'from' => 'no-reply@yourdomain.com',
'subject' => 'B',
'html' => '<p>B</p>',
],
];
[$data, $error] = $client->emails->batch($emails);
if ($error) {
echo "Batch send failed: " . $error['message'];
} else {
echo "Batch sent successfully";
}Idempotent Retries
To safely retry requests, you can pass an options array with an idempotencyKey.
// For single email
$client->emails->send($email, ['idempotencyKey' => 'unique-key-123']);
// For batch emails
$client->emails->batch($emails, ['idempotencyKey' => 'batch-unique-key-123']);Retrieve and manage emails
You can retrieve details of sent emails, update scheduled emails, or cancel them.
Get an email
Fetch the status and details of a specific email using its ID:
<?php
[$email, $error] = $client->emails->get('email_123');
if ($email) {
echo "Email Status: " . $email['status'];
}Update schedule time
Change the scheduled delivery time for a pending email:
<?php
use DateTime;
[$data, $error] = $client->emails->update('email_123', [
'scheduledAt' => new DateTime('+1 hour'),
]);Cancel a scheduled email
Cancel a scheduled email so it won't be sent:
<?php
[$data, $error] = $client->emails->cancel('email_123');Contacts
Manage your contacts and organize them into contact books. All contact operations require a contact book ID ($bookId).
Create a contact
Add a new contact to a specific contact book. You can include custom properties.
<?php
[$data, $error] = $client->contacts->create('book_123', [
'email' => 'user@example.com',
'firstName' => 'Jane',
'properties' => ['plan' => 'pro'],
]);Get a contact
Retrieve a contact's details:
<?php
[$contact, $error] = $client->contacts->get('book_123', 'contact_456');Update a contact
Update a contact's information:
<?php
[$data, $error] = $client->contacts->update('book_123', 'contact_456', [
'subscribed' => false,
]);Upsert a contact
Use upsert to create a contact if they don't exist, or update them if they do.
<?php
[$data, $error] = $client->contacts->upsert('book_123', 'contact_456', [
'email' => 'user@example.com',
'firstName' => 'Jane',
]);Delete a contact
Remove a contact from a book:
<?php
[$data, $error] = $client->contacts->delete('book_123', 'contact_456');Campaigns
Campaigns allow you to send emails to all contacts in a specific contact book.
Create a campaign
Create a new campaign by defining its content and the target contact book.
<?php
[$data, $error] = $client->campaigns->create([
'name' => 'Welcome Series',
'from' => 'welcome@example.com',
'subject' => 'Welcome to our service!',
'html' => '<p>Thanks for joining us!</p>',
'contactBookId' => 'cb_1234567890',
]);Get a campaign
Retrieve details of a specific campaign.
<?php
[$campaign, $error] = $client->campaigns->get('campaign_123');Schedule a campaign
Schedule the campaign to be sent at a specific time.
<?php
[$data, $error] = $client->campaigns->schedule('campaign_123', [
'scheduledAt' => '2024-12-01T10:00:00Z',
]);Pause/Resume a campaign
Control the delivery of your campaign.
<?php
// Pause
[$data, $error] = $client->campaigns->pause('campaign_123');
// Resume
[$data, $error] = $client->campaigns->resume('campaign_123');Domains
Manage your sending domains.
List domains
Get a list of all domains and their statuses.
<?php
[$domains, $error] = $client->domains->list();
if (!$error) {
foreach ($domains as $domain) {
echo "Domain: {$domain['name']}, Status: {$domain['status']}\n";
}
}Create a domain
Register a new domain for sending.
<?php
[$data, $error] = $client->domains->create([
'name' => 'example.com',
'region' => 'us-east-1',
]);Verify a domain
Check the verification status of a domain.
<?php
[$data, $error] = $client->domains->verify(123);Get a domain
Retrieve details of a specific domain.
<?php
[$domain, $error] = $client->domains->get(123);Delete a domain
Remove a domain from your account.
<?php
[$data, $error] = $client->domains->delete(123);Error handling
The SDK supports two modes of error handling.
Raising Exceptions (Default)
By default, the SDK raises UnsentHTTPError exceptions for non-2xx responses. This is useful if you want to use try-catch blocks.
<?php
use Souravsspace\Unsent\Unsent;
use Souravsspace\Unsent\UnsentHTTPError;
$client = new Unsent('un_xxx');
try {
[$data, $_] = $client->emails->get('email_123');
} catch (UnsentHTTPError $e) {
echo "Request failed: HTTP {$e->statusCode} - {$e->error['message']}\n";
}Returning Error Tuples
If you prefer to handle errors as return values without exceptions, pass false as the third argument to the constructor.
<?php
// Pass false to disable exceptions
$client = new Unsent('un_xxx', null, false);
[$data, $error] = $client->emails->get('email_123');
if ($error) {
echo "Error: {$error['message']}\n";
} else {
echo "Success!";
}