Skip to content

About

Official PHP library for OxiMailing (send emails, campaigns, manage tracking and account...).

Topics

Resources

Stars

3 stars

Watchers

2 watching

Forks

Latest commit

 

History

18 Commits

Folders and files

Repository files navigation

Official OxiMailing PHP Wrapper

MIT License Current Version

This repository contains the official PHP wrapper for the OxiMailing API. You don't need to know the API to use it: every route is wrapped in a documented method.

OxiMailing lets you send your emails quickly and easily, in the best possible conditions: transactional emails, newsletters and large campaigns, with a strong focus on deliverability. Founded in 2004, we're a small team recognized for the quality of our support and expertise.

To get started, create an account and request your free credits on account.oxemis.com.

Table of contents

Requirements

  • PHP 8.1 or higher, with the json and fileinfo extensions.
  • An OxiMailing API key (login and password), created in your OxiMailing account.

Installation

composer require oxemis/oximailing

Quick start

Store your API key in environment variables:

export OXIMAILING_API_LOGIN='your API login'
export OXIMAILING_API_PWD='your API password'

Then create the client and send your first email:

<?php
require_once 'vendor/autoload.php';

use Oxemis\OxiMailing\OxiMailingClient;
use Oxemis\OxiMailing\Objects\Message;

$client = new OxiMailingClient(getenv('OXIMAILING_API_LOGIN'), getenv('OXIMAILING_API_PWD'));

$message = (new Message())
    ->setSender("support@example.com")       // must be a validated sender (see "Senders")
    ->setSenderName("Your company")
    ->setSubject("Hello world!")
    ->setHtmlMessage("<p>Hi there! This is my first email sent with oximailing-php.</p>")
    ->addRecipientEmail("joe@example.com")
    ->addRecipientEmail("jane@example.com");

$sending = $client->sendAPI->send($message);
echo "Sending ID: " . $sending->getSendingId() . "\n";

OxiMailing sends 2 emails, one to joe@example.com and one to jane@example.com: Joe doesn't see Jane and vice versa.

The examples below assume $client is created as above.

Client options

The constructor accepts an optional third parameter:

$client = new OxiMailingClient($login, $password, [
    'timeout'         => 30,              // maximum duration of a request, in seconds (default 30)
    'connect_timeout' => 10,              // maximum duration of the connection (default 10)
    'max_retries'     => 3,               // retries on HTTP 429 "too many requests" (default 3)
    'user_agent'      => 'MyApp/2.1',     // appended to the User-Agent header
    // 'base_url'     => 'https://api.oximailing.com',
    // 'handler'      => $guzzleHandlerStack,   // for your tests (Guzzle MockHandler)
]);

The API accepts 10 requests per second per IP address. When it answers HTTP 429, the library waits for the delay given by the Retry-After header and tries again, up to max_retries times.

All the components share one HTTP client.

Error handling

Every method throws Oxemis\OxiMailing\OxiMailingException on failure:

use Oxemis\OxiMailing\OxiMailingException;

try {
    $client->sendAPI->send($message);
} catch (OxiMailingException $e) {
    echo $e->getCode();          // HTTP status (400, 401, 403, 404, 406...), 0 for a network error
    echo $e->getMessage();       // message of the API
    if ($e->getReason() === OxiMailingException::REASON_UNKNOWN_MERGE_FIELDS) {
        // {{fields}} of the message are missing in the MetaData of some recipients
        print_r($e->getDetails()); // [["Field" => "FirstName", "MissingFor" => 12], ...]
    }
    if ($e->getReason() === OxiMailingException::REASON_DATA_QUALITY) {
        // too many invalid or filtered recipients: the sending was refused
    }
    // $e->getHttpStatus(), $e->getResponseBody(), $e->getPrevious() (network errors)
}

Invalid arguments (unknown client option, statistics without sending IDs nor dates...) throw InvalidArgumentException.

Your account

use Oxemis\OxiMailing\Objects\User;

$user = $client->userAPI->getUser();

echo "Company: " . $user->getCompanyName() . "\n";
echo "Credits: " . $user->getCredits() . "\n";
echo "Credits valid until (included): " . $user->getCreditsValidBefore()?->format('Y-m-d') . "\n";
echo "Subscription: " . $user->getSubscription() . " emails per month\n";
echo "Used this month: " . $user->getSubscriptionUsedThisMonth() . "\n";
echo "Daily limit: " . ($user->getDailyLimit() ?? 'n/a') . "\n";

if ($user->hasFeature(User::FEATURE_RECIPIENT_ATTACHMENTS)) {
    echo "Recipients may carry their own attachments\n";
}
foreach ($user->getTrackingAccountList() as $account) {
    echo $account->getId() . " " . $account->getCaption() . "\n";
}
if ($user->getScheduledMaintenanceStart()) {
    echo "Maintenance planned on " . $user->getScheduledMaintenanceStart()->format(DATE_RFC3339) . "\n";
}

Calendar days (getCreditsValidBefore(), getSubscriptionValidFrom(), getSubscriptionValidBefore()) are returned at 00:00, Paris time, and are included: credits valid before 2026-12-31 can be used on December 31.

Senders

To send from an address, it must be a validated sender of your account, or belong to an authenticated domain. When you add a sender, a validation email is sent to it: the address stays pending until the link of this email is clicked. Senders can also be managed on this page.

$client->sendersAPI->addSender("news@example.com", "en");   // "en" or "fr": language of the validation email

$senders = $client->sendersAPI->getSenders();
print_r($senders->getValidated());   // ["support@example.com", ...]
print_r($senders->getPending());     // ["news@example.com"]

$client->sendersAPI->deleteSender("news@example.com");

Domains

Authenticate your domains (SPF, DKIM, DMARC) to improve your deliverability, and customize the tracking links with your own domain.

use Oxemis\OxiMailing\Components\DomainsAPI;

$client->domainsAPI->addDomain("example.com");

$domain = $client->domainsAPI->getDomain("example.com", DomainsAPI::LANGUAGE_EN);
echo "Guide: " . $domain->getDocumentation() . "\n";
echo "SPF: " . ($domain->isSpfValid() ? "OK" : "KO") . ", DKIM: " . ($domain->isDkimValid() ? "OK" : "KO") . "\n";
print_r($domain->getAuthDetail());   // records to create, expected values, last checks...

// After changing your DNS records
$client->domainsAPI->refreshDomain("example.com");

// Check the SPF records of your domains for OxiMailing
foreach ($client->domainsAPI->checkSpf() as $check) {
    echo $check->getDomain() . ": " . $check->getResult() . " - " . $check->getDetail() . "\n";
}

// Tracking links on stats.example.com: create a CNAME stats.example.com pointing to
// $domain->getAuthDetail()["TRCK"]["TRCK_dns_redirectto"]. HTTPS is managed by OxiMailing.
$client->domainsAPI->setTrackingByDns("example.com", "stats");

// Or with redirection scripts uploaded on your website
$client->domainsAPI->setTrackingByFiles("example.com", "/o.php", "/c.php", "/d.php", true, "www");

// Domains bought through OxiMailing
foreach ($client->domainsAPI->getReservedDomains() ?? [] as $reserved) {
    echo $reserved->getDomain() . " ready: " . ($reserved->isReady() ? "yes" : "no") . "\n";
}

Sending emails

A Message holds the content, the recipients and the options of a sending; $client->sendAPI->send() sends it. Every method of Message is documented with PHPDoc.

use Oxemis\OxiMailing\Objects\Message;

$message = (new Message())
    ->setSender("support@example.com")
    ->setSenderName("Your company")
    ->addReplyTo("contact@example.com")
    ->setSubject("Your order")
    ->setHtmlMessage("<p>Thank you for your order.</p>")
    ->setTxtMessage("Thank you for your order.")    // optional: generated from the HTML when empty
    ->addRecipientEmail("jane@example.com", "Jane Doe")
    ->addCc("sales@example.com")                    // 3 CC and 3 BCC at most; they get a copy of EVERY email
    ->addCustomHeader("X-Order-Id", "2026-001");

$sending = $client->sendAPI->send($message);

echo "Sending ID: " . $sending->getSendingId() . "\n";
print_r($sending->getOKEmails());        // accepted
print_r($sending->getFilteredEmails());  // blocked: bounce list, unsubscribe list or red lists
print_r($sending->getInvalidEmails());   // blocked: invalid address

Each call to send() is followed by a short pause on the API side: put many recipients in one message (or use sendMultiple()) rather than making one call per email.

Personalized messages

Every {{Key}} of the subject and the content is replaced by the value of the recipient's metadata (keys are compared without case):

use Oxemis\OxiMailing\Objects\Message;
use Oxemis\OxiMailing\Objects\Recipient;

$jane = new Recipient();
$jane->setEmail("jane@example.com");
$jane->setName("Jane Doe");
$jane->setMetaData(["FirstName" => "Jane", "CustomerId" => 1]);
$jane->setToken("CUSTOMER-1");   // your own reference, echoed back in the events

$joe = new Recipient();
$joe->setEmail("joe@example.com");
$joe->setMetaData(["FirstName" => "Joe", "CustomerId" => 2]);

$message = (new Message())
    ->setSender("support@example.com")
    ->setSubject("Hello {{FirstName}}!")
    ->setHtmlMessage("<p>Hi {{FirstName}}, your customer ID is {{CustomerId}}.</p>")
    ->addRecipient($jane)
    ->addRecipient($joe);

$client->sendAPI->send($message);

If a {{field}} is missing for some recipients, the sending is refused with REASON_UNKNOWN_MERGE_FIELDS (see Error handling); an empty value is allowed.

Attachments and inline images

use Oxemis\OxiMailing\Objects\Attachment;

$message
    ->addAttachment("/path/to/terms.pdf")                                  // sent to every recipient
    ->addInlineAttachment("/path/to/logo.png", "logo")                     // <img src="cid:logo"/>
    ->setHtmlMessage('<p><img src="cid:logo"/></p><p>Hello!</p>');

// From a string (a PDF generated in memory, for example)
$message->setAttachments([Attachment::fromContent($pdfContent, "offer.pdf", "application/pdf")]);

Attachments for one recipient

Each recipient can receive its own files (an invoice, a statement...), in one call for many recipients:

use Oxemis\OxiMailing\Objects\Message;
use Oxemis\OxiMailing\Objects\Recipient;
use Oxemis\OxiMailing\Objects\User;

if (!$client->userAPI->getUser()->hasFeature(User::FEATURE_RECIPIENT_ATTACHMENTS)) {
    throw new RuntimeException("This version of the API doesn't support attachments per recipient.");
}

$message = (new Message())
    ->setSender("billing@example.com")
    ->setSubject("Your invoice {{InvoiceNumber}}")
    ->setHtmlMessage("<p>Please find your invoice attached.</p>");

foreach ($invoices as $invoice) {   // your data
    $recipient = new Recipient();
    $recipient->setEmail($invoice['email']);
    $recipient->setMetaData(["InvoiceNumber" => $invoice['number']]);
    $recipient->addAttachment($invoice['pdf_path'], "invoice-" . $invoice['number'] . ".pdf");
    $message->addRecipient($recipient);
}

$client->sendAPI->send($message);

Each email (message + its recipient's attachments) must stay under the maximum size of a message.

Special links: unsubscribe, tracking consent, links not tracked

In the HTML of the message:

Code Effect
<a href="#UNSUB#">Unsubscribe</a> Unsubscribe link: the recipient is added to the unsubscribe list of the tracking account.
<a href="#UNSUBALL#">Unsubscribe from everything</a> Global unsubscribe link: the recipient is added to the unsubscribe lists of all your tracking accounts.
<a href="#TRCKCONSENT#">Manage my consent</a> Page where the recipient manages its consent to tracking (legal requirement in France since July 2026).
<a href="https://www.example.com" data-notrack="1"> This link is not tracked (kept as is; the attribute is removed).

These links require tracking: the API enables it when they are present.

Tracking consent. Opens are only measured for recipients who consent to it (GDPR / French CNIL); clicks are always recorded. Give the consent of each named recipient:

$recipient->setTrackingConsent(true);    // or false; not set: tracked until September 30, 2026, declining after

When sending to a contact list, the consent is read from each contact. By default, #TRCKCONSENT# points to the consent page of the tracking server, and OxiMailing remembers the choice of each recipient. To use your own page (OxiMailing then relies only on the consent you send):

$message->setTrackingConsentCustomLink("https://www.example.com/consent?email={{email}}");

Options of a sending

$message
    ->setTrackEmails(true)               // track opens, clicks, unsubscriptions and bounces
    ->setTrackingLogin("ID_OF_ACCOUNT")  // tracking account (and its unsubscribe list); default account if empty
    ->setCampaignName("November newsletter")
    ->setNewSending(true)                // new sending ID even within one hour of a sending of the same campaign
    ->setAllowDuplicates(false);

// Premium accounts only: send an individual service message (invoice, password reset...) to recipients of
// the unsubscribe list. Never for marketing messages. Bounces and red lists still apply.
$message->setUseBlacklist(false);

By default, sendings of the same campaign made less than one hour apart share one sending ID: use a distinct campaign name, or setNewSending(true), when you need one ID per call.

Sending to a contact list

$message = (new Message())
    ->setSender("news@example.com")
    ->setSubject("Hello {{FirstName}}")
    ->setHtmlMessage("<p>Hi {{FirstName}}!</p> <a href=\"#UNSUB#\">Unsubscribe</a>")
    ->setTrackEmails(true)
    ->setList(45, "{{FirstName}} {{LastName}}");   // list ID, and template of the display name (optional)

$client->sendAPI->send($message);

A message is sent either to named recipients or to a list, never both.

Scheduling, checking the capacity, several sendings

// Can I send 5000 emails tomorrow at 10:00? Nothing is sent nor consumed.
$date = new DateTime("tomorrow 10:00", new DateTimeZone("Europe/Paris"));
$check = $client->sendAPI->checkCapacity(5000, $date);
if (!$check->canSend()) {
    echo "Refused: " . $check->getReason() . "\n";   // CapacityCheck::REASON_NOT_ENOUGH_CREDIT_DAY...
    echo "Remaining that day: " . $check->getDetails()[0]->getDailyRemaining() . "\n";
}

// Schedule (at least 5 minutes ahead)
$message->setScheduledDateTime($date);
$client->sendAPI->send($message);

foreach ($client->sendAPI->getScheduled() ?? [] as $scheduled) {
    echo $scheduled->getSendingId() . " " . $scheduled->getScheduledDateTime()?->format(DATE_RFC3339) . "\n";
}
$client->sendAPI->deleteScheduled(123456);

// Several messages in one call: checked together, none is sent if one is refused
$results = $client->sendAPI->sendMultiple([$message1, $message2]);

Contact lists

use Oxemis\OxiMailing\Components\ListsAPI;

$list = $client->listsAPI->createList("Newsletter", ["FirstName", "LastName"]);

$result = $client->listsAPI->addContacts($list->getId(), [
    "jane@example.com" => ["FirstName" => "Jane", "LastName" => "Doe"],
    "joe@example.com"  => ["FirstName" => "Joe", "LastName" => "Smith"],
], ListsAPI::MODE_UPDATE);   // MODE_IGNORE (default), MODE_INSERT or MODE_UPDATE
echo $result->getAdded() . " added, " . $result->getUpdated() . " updated\n";

foreach ($client->listsAPI->getLists(false, false) as $l) {   // false, false: faster, without counting
    echo $l->getId() . " " . $l->getName() . "\n";
}

// One page of contacts
$page = $client->listsAPI->getContacts($list->getId(), 100, 0);
echo $page->getTotal() . " contacts\n";
foreach ($page->getContacts() as $contact) {
    echo $contact['email'] . "\n";
}

// Or every contact, page by page
foreach ($client->listsAPI->iterateContacts($list->getId()) as $contact) {
    // ...
}

$client->listsAPI->deleteContacts($list->getId(), ["joe@example.com"]);
$client->listsAPI->renameList($list->getId(), "Newsletter 2027");
$client->listsAPI->deleteList($list->getId());

Unsubscribe lists and bounce list

Recipients of your unsubscribe lists (one per tracking account) and of your bounce list (invalid addresses) are filtered out of your sendings. For historical reasons, the unsubscribe lists are handled by $client->blacklistsAPI (route /blacklists).

// Add or remove addresses
$client->blacklistsAPI->addEmails(["jane@example.com", "joe@example.com"]);
$client->blacklistsAPI->removeEmails("jane@example.com");
$client->bouncesAPI->addEmails(["old@example.com"]);

// Read with details (date and source of each unsubscription)
$page = $client->blacklistsAPI->getEntries(-1, 5000, true);
foreach ($page->getEntries() as $entry) {
    echo $entry->getEmail() . " " . $entry->getSource() . " " . $entry->getDateAdded()?->format('Y-m-d') . "\n";
}

// Bounce list with the type and the reason of each bounce
foreach ($client->bouncesAPI->iterateEntries(-1, 5000, true) as $bounce) {
    echo $bounce->getEmail() . " " . $bounce->getType() . " " . $bounce->getReason() . "\n";
}

Incremental synchronisation. Store the sync version and the highest ID you received; next time, download only what changed:

$page = $client->blacklistsAPI->getEntries($myLastId, 5000);
if ($page->getSyncVersion() !== $mySyncVersion) {
    // addresses were removed since your last synchronisation: download the whole list again
    $page = $client->blacklistsAPI->getEntries(-1, 5000);
}
$mySyncVersion = $page->getSyncVersion();
$myLastId = $page->getMaxId() ?? $myLastId;   // and continue with the next pages while they are full

// With several tracking accounts: the counters of all of them in one call
foreach ($client->blacklistsAPI->getSyncInfo() as $info) {
    echo $info->getId() . " version " . $info->getSyncVersion() . " last ID " . $info->getLastId() . "\n";
}

Spam complaints

foreach ($client->complaintsAPI->getComplaints() ?? [] as $complaint) {
    echo $complaint->getEmail() . " via " . $complaint->getComplaintOperator() . "\n";
}

Tracking: events, statistics, reports

Enable tracking on the message (setTrackEmails(true)), then:

use Oxemis\OxiMailing\Objects\Event;

// Events of a sending (several types at once)
$events = $client->trackingAPI->getEvents([Event::EVENT_TYPE_OPEN, Event::EVENT_TYPE_CLICK], null, null, null, $sendingId);
foreach ($events ?? [] as $event) {
    echo $event->getEventType() . " " . $event->getEventEmail() . " " . ($event->getEventInfo()['URL'] ?? '') . "\n";
}

// Between two dates (no limit on the length; $end excluded; start at most 3 years ago)
$events = $client->trackingAPI->getEvents(Event::EVENT_TYPE_UNSUB, null, new DateTime("-30 days"), new DateTime());

// Statistics summed over several sendings, or over a period
$stats = $client->trackingAPI->getStatistics([102639202, 102639203]);
echo $stats?->getNbOpeners() . " openers, " . $stats?->getNbClickers() . " clickers\n";

// One entry per sending
$bySending = $client->trackingAPI->getStatisticsBySending(null, new DateTime("-30 days"));
foreach ($bySending?->getSendings() ?? [] as $s) {
    echo $s->getSendingId() . " " . $s->getCampaignName() . " " . $s->getNbOpeners() . "/" . ($s->getNbConsenting() ?? $s->getNbRecipients()) . "\n";
}

// Report URLs (one per tracking campaign)
foreach ($client->trackingAPI->getReports([102639202, 102639203], "en") as $report) {
    echo $report->getUrl() . "\n";
}

The open rate is computed on the recipients who consented to open tracking (getNbConsenting(), or getNbRecipients() when unknown); clicks and unsubscriptions on getNbRecipients().

Tracking accounts

Each tracking account has its own unsubscribe list and records its own events. Most accounts have only one.

foreach ($client->trackingAccountsAPI->getTrackingAccounts() as $account) {
    echo $account->getId() . " " . $account->getCaption() . "\n";
}
$client->trackingAccountsAPI->renameTrackingAccount("ID_OF_ACCOUNT", "Brand A");   // 25 characters at most

Pass the ID as $trackingAccountId to the methods of the other components, or to Message::setTrackingLogin().

Callbacks

OxiMailing can post the recorded events to a URL of yours. It must answer OK (HTTP 200) when called with test=1, and when it receives the posted file data.json (same structure as the data part of the events).

$client->callbacksAPI->setCallback("https://www.example.com/oximailing-callback.php", 300);

$callback = $client->callbacksAPI->getCallback();
echo $callback?->getUrl() . " last OK: " . $callback?->getLastOK()?->format(DATE_RFC3339) . "\n";

$client->callbacksAPI->deleteCallback();

History and delivery logs

use Oxemis\OxiMailing\Components\HistoryAPI;

// Sendings of your program in the last 30 days (365 days at most)
$sendings = $client->historyAPI->getSendings(HistoryAPI::TYPE_ALL, new DateTime("-30 days"), new DateTime(), null, HistoryAPI::SOURCE_API);
foreach ($sendings as $sending) {
    echo $sending->getSendingId() . " " . $sending->getStartDate()?->format('Y-m-d H:i') . " " . $sending->getSubject() . "\n";
}

// Technical answers of the server of a recipient (7 days at most; logs must be activated by the support)
foreach ($client->historyAPI->getLogs("jane@example.com") as $log) {
    echo $log->getDate()?->format(DATE_RFC3339) . " " . $log->getLog() . "\n";
}

Tools

// SPF record of any domain
$spf = $client->toolsAPI->checkSpf("example.com");
echo $spf->getSpf() . " => " . $spf->getResult() . "\n";

// Links of an HTML content
foreach ($client->toolsAPI->checkLinks($html) as $link) {
    if (!$link->isLinkAccessible()) {
        echo "Broken link: " . $link->getLink() . " (" . $link->getStatus() . ")\n";
    }
}

Cloud

Store the images and documents of your messages on the OxiMailing cloud, and use their public URL.

$space = $client->cloudAPI->getSpace();
echo $space->getAvailable() . " MB available\n";

$client->cloudAPI->createFolder("newsletters", "/");
$file = $client->cloudAPI->uploadFile("/path/to/banner.png", "/newsletters", true);
echo "Public URL: " . $file->getHttp() . "\n";

foreach ($client->cloudAPI->listFiles("/newsletters", false) as $f) {
    echo $f->getName() . " " . $f->getSize() . " bytes\n";
}

file_put_contents("/tmp/banner.png", $client->cloudAPI->downloadFile("banner.png", "/newsletters"));
$client->cloudAPI->renameFile("banner.png", "banner-2026.png", "/newsletters");
$client->cloudAPI->deleteFile("banner-2026.png", "/newsletters");

Campaigns of the OxiMailing software. The cloud also stores the campaigns of the OxiMailing software (.oximailing files, .emailing for the former software), in their own folders:

foreach ($client->cloudAPI->listCampaigns() as $campaign) {
    echo $campaign->getPath() . "/" . $campaign->getName() . "\n";
}
$client->cloudAPI->createCampaignFolder("Archive");
$client->cloudAPI->moveCampaign("offer.oximailing", "/Archive");
$content = $client->cloudAPI->downloadCampaign("offer.oximailing", "/Archive");

Pagination

Data Page Everything
Contacts of a list listsAPI->getContacts($listId, $limit, $offset) (getTotal()) listsAPI->iterateContacts($listId)
Unsubscribe list blacklistsAPI->getEntries($lastId, $limit) (getMaxId() = next $lastId) blacklistsAPI->iterateEntries()
Bounce list bouncesAPI->getEntries($lastId, $limit) bouncesAPI->iterateEntries()

Deprecated methods

They still work, and will be removed in a future major version:

Deprecated Use
Message::addAtachement() Message::addAttachment()
User::getSubcription() User::getSubscription()
User::getSubcriptionUsedThisMonth() User::getSubscriptionUsedThisMonth()

See CHANGELOG.md for the changes of each version.

Links

Contribute

Feel free to ask anything, and to contribute to this project (composer test runs the tests, composer analyse the static analysis). Need help? support@oxemis.com

About

Official PHP library for OxiMailing (send emails, campaigns, manage tracking and account...).

Topics

Resources

Stars

3 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages