Libraries

Icon back arrow

PHP

Elastic Email PHP API Library

Introduction

When you integrate Elastic Email with your application, you can interact with your Elastic Email account directly by our API. You can easily integrate your email flow, manage your contacts and templates, send emails, and track email statistics directly from your app.

This page will help you easily integrate with Elastic Email using the PHP library. You can find our whole downloadable PHP repository on GitHub. You can also use our comprehensive API documentation.

Elastic Email API v4 uses REST architecture, which allows you to perform various code actions, including directly through your app.

The maximum email size of your entire message or message + attachment cannot exceed 20MB.

The attachment format is the file’s content as a byte array or a Base64 string.

The maximum number of recipients has no limit for one campaign. It depends on the pricing plan.

The API has a limit of 20 concurrent connections and a hard timeout of 600 seconds per request.

On this page, you will find how to authenticate your application and what the requirements for the integration are. You will be also provided with a quick start guide on how to start using API, followed by code samples. 

If you like this article, share it with friends:

Authentication

To provide valid authentication and start using our API, you will need an API key. To generate your API key, enter settings on your Elastic Email account and go to Settings -> Manage API Keys -> Create or you can also click on the link: 

Create API key

Ceater API key

At this point, you can set custom permissions and optional access for your API key. 

Security tip: The restriction forces the API Key to work only with an IP or IP range that will be specified in this field.

Create API key 2

Once you create your API key, keep it safe as it will be used for every API call you make in order to identify you and confirm your account’s credentials. You can create either up to 15 or an unlimited amount of API keys based on your pricing plan. 

Your API key should be sent inside the header with the parameter name ‘x-elasticemail-apikey’ and your API key as a value.

Installation and Usage

Requirements

PHP 7.3 and later. Should also work with PHP 8.0 but has not been tested.

Installation

Our official downloadable PHP library is available on GitHub.

We’ve prepared for you the steps to take to install and implement our PHP library:
Install a PHP version, 7.3. or later, compatible with your operating system. You also have to install Composer. You can install the bindings via Composer by adding the following to composer.json:

Copied!
{
  "repositories": [
    {
      "type": "vcs",
      "url": "https://github.com/elasticemail/elasticemail-php.git"
    }
  ],
  "require": {
    "elasticemail/elasticemail-php": "*@dev"
  }
}

Then run composer install

After the installation procedure, run the following:

Copied!
<?php
require_once(__DIR__ . '/vendor/autoload.php');



// Configure API key authorization: apikey
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', 'YOUR_API_KEY');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKeyPrefix('X-ElasticEmail-ApiKey', 'Bearer');


$apiInstance = new ElasticEmail\Api\CampaignsApi(
    // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
    // This is optional, `GuzzleHttp\Client` will be used as default.
    new GuzzleHttp\Client(),
    $config
);
$name = 'name_example'; // string | Name of Campaign to delete

try {
    $apiInstance->campaignsByNameDelete($name);
} catch (Exception $e) {
    echo 'Exception when calling CampaignsApi->campaignsByNameDelete: ', $e->getMessage(), PHP_EOL;
}

Quick start guide

In this section, we will tell you the steps to start sending emails with our email API.

1. Register a free account

Register and activate your Elastic Email account to get access to our product.

2. Verify your domain

Follow the instructions on our settings page to verify your domain and start sending with us.

3. Create an API Key

Go to your setting to generate an API Key to add to your code later.

4. Install our libraries

Install our PHP library as explained in the Installation and usage section.

5. Send your first email with API

Now it’s time to send your first test email with API to make sure that everything is set up correctly after downloading the library and the authentication process.

Copied!
require_once('vendor/autoload.php');
 
$config = ElasticEmail\Configuration::getDefaultConfiguration()
        ->setApiKey('X-ElasticEmail-ApiKey', '895A382DF3DCC13A97E72EXAMPLEKEY');
 
$apiInstance = new ElasticEmail\Api\EmailsApi(
    new GuzzleHttp\Client(),
    $config
);
 
$email = new \ElasticEmail\Model\EmailMessageData(array(
    "recipients" => array(
        new \ElasticEmail\Model\EmailRecipient(array("email" => "mail@contact.com"))
    ),
    "content" => new \ElasticEmail\Model\EmailContent(array(
        "body" => array(
            new \ElasticEmail\Model\BodyPart(array(
                "content_type" => "HTML",
                "content" => "My content"
            ))
        ),
        "from" => "email@domain.com",
        "subject" => "My Subject"
    ))
));
 
try {
    $apiInstance->emailsPost($email);
} catch (Exception $e) {
    echo 'Exception when calling EE API: ', $e->getMessage(), PHP_EOL;
}

Code Samples

Once you have sent the test email with our API, you can start sending transactional emails and perform various operations directly through your app. We have prepared for you some code samples for most essential actions, including managing contacts and lists, creating templates, and sending and tracking emails. Thanks to them, your integration with our API will be an even easier and more pleasant experience.
In case any of the following snippets are changed in the meantime, the most recent version of this API Library is available on GitHub.

Managing Contacts

In this section, we will walk you through managing the contacts on your account using the PHP library.

Add single contact

To add a single contact to your account, you will need Access Level: ModifyContacts.

Put the following code into your file. 

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Get client instance:

Copied!
$apiInstance = new ElasticEmail\Api\ContactsApi(
    new GuzzleHttp\Client(),
    $config
);

Create an instance of ContactsApi that will be used to add contacts.

Copied!
$contact_payload = [new \ElasticEmail\Model\ContactPayload(
    [
        "email" => "work.rafkwa+test@gmail.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "status" => 'Active'
        ]
    )];
$listnames = "My Contacts 1";

response = $apiInstance->contactsPost($contact_payload, $listnames);

Add bulk contacts

Contacts can be also added in bulk. To add multiple contacts to your account, you will need Access Level: ModifyContacts.

Put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Load library using the following line:

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Get client instance:

Copied!
$apiInstance = new ElasticEmail\Api\ContactsApi(
    new GuzzleHttp\Client(),
    $config
);

Create an instance of ContactsApi that will be used to add contacts.

Copied!
$contact_payload = [new \ElasticEmail\Model\ContactPayload(
    [
        "email" => "work.rafkwa+test@gmail.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "status" => 'Active'
        ]
    )];
$listnames = "My Contacts 1";

response = $apiInstance->contactsPost($contact_payload, $listnames);

Delete contact

If you want to delete a contact, you will need Access Level: ModifyContacts.

To delete a contact, put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of ContactsApi that will be used to delete contacts.

Copied!
$apiInstance = new ElasticEmail\Api\ContactsApi(
    new GuzzleHttp\Client(),
    $config
);

Create an object with an array of contacts to delete.

Find out more by checking our API's documentation.

Create an instance of CampaignsApi that will be used to create a campaign.

Copied!
$email = ["mail@contact.com"];
$response = $apiInstance->contactsByEmailDelete($email);

Import Contacts

If you want to import contacts to your account using the PHP library, you will need Access Level: ModifyContacts.

To import contacts, put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check a required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Get client instance:

Copied!
$apiInstance = new ElasticEmail\Api\ContactsApi(
    new GuzzleHttp\Client(),
    $config
);

Create an instance of ContactsApi that will be used to add contacts.

Copied!
$list_name = "My Contacts 1";
$encoding_name = "UTF-8";
$file = "my-contacts.csv";

$response = $apiInstance->contactsImportPost($list_name, $encoding_name, $file);

Export Contacts

If you want to export the selected contact to a downloadable file, you will need Access Level: Export.

Put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

In this example we will export contacts to a CSV file. Create an instance of ContactsApi that will be used to export contacts.

Copied!
$apiInstance = new ElasticEmail\Api\ContactsApi(
    new GuzzleHttp\Client(),
    $config
);

Create an options object:

fileFormat - specify format in which file should be created, options are: "Csv" "Xml" "Json". emails - select contacts to export by providing array of emails fileName - you can specify file name of your choice

Other options:

rule - eg. rule=Status%20=%20Engaged – Query used for filtering compressionFormat - "None" "Zip"

Find out more by checking our API's documentation.

Copied!
$file_format = 'Csv';
$rule = null;
$emails = ['mail@contact.com,mail1@contact.com,mail2@contact.com'];
$compression_format = 'None';
$file_name = "my-export.csv";

$response = $apiInstance->contactsExportPost($file_format, $rule, $emails, $compression_format, $file_name)

Managing Lists

In this section, we will walk you through managing your contact list on your account using the PHP library.

Add List

To add a list, you will need Access Level: ModifyContacts.

Put the following code into your file. 

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check a required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Get client instance:

Copied!
$apiInstance = new ElasticEmail\Api\ListsApi(
    new GuzzleHttp\Client(),
    $config
);

Create an object with details about the new list. Only ListName is required.

You can also define if to allow unsubscription from the list and pass an email array of existing contacts on your account to add them to the list during list creation.

Find out more by checking our API's documentation.

Copied!
$list_payload = new \ElasticEmail\Model\ListPayload([
    "list_name" => "My New List",
    "allow_unsubscribe" => true,
    "emails" => []
]);

Load List

To load a list, you will need Access Level: ModifyContacts.

Put the following code into your file. 

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check a required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of StatisticsApi that will be used to get basic send statistics.

Copied!
$apiInstance = new ElasticEmail\Api\StatisticsApi(
    new GuzzleHttp\Client(),
    $config
);

The only thing needed is a list name.

Find out more by checking our API's documentation.

Copied!
$name = "My New List";
$response = $apiInstance->listsByNameGet($name);

Delete List

To remove a contact list from your account, you will need Access Level: ModifyContacts.

Put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of ListsApi that will be used to delete a list.

Copied!
$apiInstance = new ElasticEmail\Api\ListsApi(
    new GuzzleHttp\Client(),
    $config
);

The only thing needed is a list name.

Find out more by checking our API's documentation.

Create an instance of ListsApi that will be used to delete a list.

Copied!
$name = "My List";
$response = $apiInstance->listsByNameDelete($name);

Creating Templates

An email template is a body of email prepared and saved under a given name. In this section, you will get to know how to add and load email templates.

Add Template

To add a template, you will need Access Level: ModifyTemplates.

Put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Get client instance:

Copied!
$apiInstance = new ElasticEmail\Api\TemplatesApi(
    new GuzzleHttp\Client(),
    $config
);

Create an instance of TemplatesApi that will be used to create a new template.

Copied!
const templatesApi = new ElasticEmail.TemplatesApi();

Create an object with details about the new template:

  • Name – the name of your template by which it can be identified and used
  • Subject – specify the default subject for this template
  • Body – specify actual body content eg. in HTML, PlainText or both
  • TemplateScope – specify scope, "Personal" template won't be shared, "Global" template can be shared with your sub accounts.

Find out more by checking our API's documentation.

Copied!
$template_payload = new \ElasticEmail\Model\TemplatePayload([
    "name" => "My New Template",
    "subject" => "Newsletter",
    "body" => [new \ElasticEmail\Model\BodyPart([
        "content_type" => "HTML",
        "content" => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" lang="EN">
          <head>
            <style type="text/css">
                .mydiv {
                    background: #FFBD5A;
                    text-align: center;
                    padding: 40px;
                }
            </style>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          </head>
        <body>
        <div class="mydiv">
            <h1>My template</h1>
        </div>
        </body>
        </html>'
        ])
    ],
    "template_scope" => "Global"
]);

And finally, call templatesPost method from the API to create a template:

Copied!
$response = $apiInstance->templatesPost($template_payload);

Load Template

To load existing template details, you will need Access Level: ViewTemplates.

Put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of TemplatesApi that will be used to load a template.

Copied!
$apiInstance = new ElasticEmail\Api\TemplatesApi(
    new GuzzleHttp\Client(),
    $config
);

To load a template, you need to specify its name:

Find out more by checking our API's documentation.

Copied!
$name = "My New List";
$response = $apiInstance->listsByNameGet($name);

Sending Emails

In this section, we will tell you how you can start sending emails using the PHP library. You will get to know how to send bulk and transactional emails.

Send Transactional Emails

To send transactional emails, you will need Access Level: SendHttp.

Put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of EmailsApi that will be used to send a transactional email.

Copied!
$apiInstance = new ElasticEmail\Api\EmailsApi(
    new GuzzleHttp\Client(),
    $config
);

First, you need to specify email details:

email recipients:

this example demonstrates merge fields usage, for each recipient {name} will be changed to the recipient's name

email content:

body parts – in HTML, PlainText or in both from email – it needs to be your validated email address email subject

Find out more by checking our API's documentation.

Copied!
$email_message_data = new \ElasticEmail\Model\EmailTransactionalMessageData([
    "recipients" => new \ElasticEmail\Model\TransactionalRecipient([
        "to" => ["email@domain.com, email2@domain.com, email3@domain.com"],
        "cc" => ["email4@domain.com, email5@domain.com"],
        "bcc" => ["email6@domain.com"]
    ]),
    "content" => new \ElasticEmail\Model\EmailContent([
        "body" => [new \ElasticEmail\Model\BodyPart([
                "content_type" => "HTML",
                "content" => "My test email content"
            ])
        ],
        "from" => "mail@contact.com",
        "subject" => "My Subject",
        "reply_to" => "mail@contact.com",
    ]),
    "options" => new \ElasticEmail\Model\Options([
        "channel_name" => "My Channel"
    ])
]);

$response = $apiInstance->emailsTransactionalPost($email_message_data);

Send Bulk Emails

Put the following code to your file to send a bulk email, meaning a single email sent to a large group at once.

You will need Access Level: SendHttp.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of EmailsApi that will be used to send a bulk email.

Copied!
$apiInstance = new ElasticEmail\Api\EmailsApi(
    new GuzzleHttp\Client(),
    $config
);

First, you need to specify email details:

email recipients:

this example demonstrates merge fields usage, for each recipient {name} will be changed to the recipient's name

email content:

body parts – in HTML, PlainText or in both from email – it needs to be your validated email address email subject

Find out more by checking our API's documentation.

Copied!
$email_message_data = new \ElasticEmail\Model\EmailMessageData([
    "recipients" => [new \ElasticEmail\Model\EmailRecipient([
        "email" => "email@domain.com"
    ])],
    "content" => new \ElasticEmail\Model\EmailContent([
        "body" => [new \ElasticEmail\Model\BodyPart([
                "content_type" => "HTML",
                "content" => "My test email content"
            ])
        ],
        "from" => "mail@contact.com",
        "subject" => "My Subject",
        "reply_to" => "mail@contact.com",
    ]),
    "options" => new \ElasticEmail\Model\Options([
        "channel_name" => "My Channel"
    ])
]);

$response = $apiInstance->emailsPost($email_message_data);

Managing Campaigns

Add Campaign

To add your first campaign using the PHP library, you will need Access Level: ModifyCampaigns. Mind that when using Elastic Email, when you send an email to any group of contacts, we call it a “campaign”.

To add a campaign, put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Get client instance:

Copied!
$apiInstance = new ElasticEmail\Api\CampaignsApi(
    new GuzzleHttp\Client(),
    $config
);

Create an example campaign object:

Name: defines the campaign name by which you can identify it later

Recipients: define your audience

Content: define your message details

Status: define the status in which the campaign should be created

Find out more by checking our API's documentation.

Copied!
$campaign = new \ElasticEmail\Model\Campaign([
    "name" => "My Campaign",
    "recipients" => new \ElasticEmail\Model\CampaignRecipient([
            "list_names" => ["My Contacts 1"]
    ]),
    "content" => [
        new \ElasticEmail\Model\CampaignTemplate([
            "poolname" => "My Custom Pool",
            "from" => "email@domain.com",
            "reply_to" => "email@domain.com",
            "subject" => "Hello",
            "template_name" => "Template-name",
        ])
    ],
]);

Create an instance of CampaignsApi that will be used to create a campaign.

Copied!
$response = $apiInstance->campaignsPost($campaign);

Delete Campaign

To delete an existing campaign, you will need Access Level: ModifyCampaigns. Mind that when using Elastic Email, when you send an email to any group of contacts, we call it a “campaign”.

To delete a campaign, put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of CampaignsApi that will be used to delete a campaign.

Copied!
$apiInstance = new ElasticEmail\Api\CampaignsApi(
    new GuzzleHttp\Client(),
    $config
);

The only thing you need to specify is a campaign name

Find out more by checking our API's documentation.

Copied!
$name = "My Campaign 1";
$response = $apiInstance->campaignsByNameDelete($name);

Load Campaign

To load details about an existing campaign in your account using the PHP library, you will need Access Level: ViewCampaigns. Mind that when using Elastic Email, when you send an email to any group of contacts, we call it a “campaign”.

To load a campaign, put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of CampaignsApi that will be used to load a campaign.

Copied!
$apiInstance = new ElasticEmail\Api\CampaignsApi(
    new GuzzleHttp\Client(),
    $config
);

The only thing you need to specify is a campaign name

Find out more by checking our API's documentation. 

Copied!
$name = "My Campaign 1";
$response = $apiInstance->campaignsGet($name);

Load Campaigns

To load details about existing campaigns in your account using the PHP library, you will need Access Level: ViewCampaigns. Mind that when using Elastic Email, when you send an email to any group of contacts, we call it a “campaign”.

To load campaigns, put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of CampaignsApi that will be used to load campaigns.

Copied!
$apiInstance = new ElasticEmail\Api\CampaignsApi(
    new GuzzleHttp\Client(),
    $config
);

Find out more by checking our API's documentation.

Copied!
$response = $apiInstance->campaignsGet();

Update Campaign

To update existing campaigns in your account using the PHP library, you will need Access Level: ViewCampaigns. Mind that when using Elastic Email, when you send an email to any group of contacts, we call it a “campaign”.

To update a campaign, put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of CampaignsApi that will be used to update a campaign.

Copied!
$apiInstance = new ElasticEmail\Api\CampaignsApi(
    new GuzzleHttp\Client(),
    $config
);

Create a whole campaign object that you want to put in place of a current version:

Name: defines campaign name by which you can identify it later Recipients: define your audience Content: define your message details Status: define status in which campaign should be created

Send will be triggered immediately or postponed, depending on the given options. Because we define Status as Draft, in this case, it will be postponed, and the campaign will be added to drafts.

Find out more by checking our API's documentation. 

Copied!
$name = "My Campaign 1";
$campaign = new \ElasticEmail\Model\Campaign([
    "recipients" => new \ElasticEmail\Model\CampaignRecipient([
            "list_names" => ["My Contacts 1"]
    ]),
    "content" => [
        new \ElasticEmail\Model\CampaignTemplate([
            "poolname" => "My Custom Pool",
            "from" => "email@domain.com",
            "reply_to" => "email@domain.com",
            "subject" => "New Subject",
            "template_name" => "Template-name"
        ])
    ],
]);

$response = $apiInstance->campaignsByNamePut($name, $campaign);

Tracking

In this section, we will walk you through the steps of managing actions related to email tracking. You will get to know how to load delivery and campaign statistics from your account using the PHP library.

Load Statistics

To load delivery statistics from your account, you will need Access Level: ViewReports.

Put the following code into your file.

Load library using the line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Get client instance:

Copied!
$apiInstance = new ElasticEmail\Api\StatisticsApi(
    new GuzzleHttp\Client(),
    $config
);

First, you need to specify a date range:

  • from date
  • to date – optional

Find out more by checking our API's documentation. 

Copied!
$from = "2022-03-14T12:00:00+01:00";
$to = "2022-03-17T12:00:00+01:00";

Create an instance of StatisticsApi that will be used to get basic send statistics.

Copied!
$response = $apiInstance->statisticsGet($from, $to);

Load Channel Statistics

To load statistics for each channel from your account, you will need Access Level: ViewChannels.

Put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check a required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of StatisticsApi that will be used to get basic send statistics.

Copied!
$apiInstance = new ElasticEmail\Api\StatisticsApi(
    new GuzzleHttp\Client(),
    $config
);

Find out more by checking our API's documentation.

Copied!
$limit = 100;
$offset = 20;
$response = $apiInstance->statisticsChannelsGet($limit, $offset);

Load Campaigns Stats

To load statistics for each email campaign from your account, you will need Access Level: ViewChannels.

Put the following code into your file.

Load library using the following line:

Copied!
require_once(__DIR__ . '/vendor/autoload.php');

Generate and use your API key (remember to check the required access level):

Copied!
define('MY_APIKEY', 'YOUR_API_KEY');
$config = ElasticEmail\Configuration::getDefaultConfiguration()->setApiKey('X-ElasticEmail-ApiKey', MY_APIKEY);

Create an instance of StatisticsApi that will be used to get basic send statistics.

Copied!
$apiInstance = new ElasticEmail\Api\CampaignsApi(
    new GuzzleHttp\Client(),
    $config
);

Find out more by checking our API's documentation.

Copied!
$response = $apiInstance->campaignsGet();
If you like this article, share it with friends:

Ready to get started?

Tens of thousands of companies around the world already send their emails with Elastic Email. Join them and discover your own email superpowers.

Icon green check Instant setup Icon green check No credit card required