Libraries

JavaScript

Elastic Email JavaScript 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 Javascript library. You can find our whole downloadable Javascript repository on GitHub here. If you need API documentation, you can find it here.

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: 

https://elasticemail.com/account#/settings/new/create-api

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

Installation

Our official downloadable Javascript library is available on GitHub.

We’ve prepared for you the steps to take to install and implement our Javascript library:

If you want to install the repository with Node.js

npm

To publish the library as an npm, please follow the procedure in "Publishing npm packages".

Then install it via:

Copied!
npm install @elasticemail/elasticemail-client --save

Finally, you need to build the module:

Copied!
npm run build
Local development

To use the library locally without publishing to a remote npm registry, first install the dependencies by changing into the directory containing package.json (and this README). Let's call this JAVASCRIPT_CLIENT_DIR. Then run:

Copied!
npm install

Next, link it globally in npm with the following, also from JAVASCRIPT_CLIENT_DIR:

Copied!
npm link

To use the link you just defined in your project, switch to the directory you want to use your @elasticemail/elasticemail-client from, and run:

Copied!
npm link /path/to/

Finally, you need to build the module:

Copied!
npm run build

git

If the library is hosted at a git repository, e.g.https://github.com/elasticemail/elasticemail-js then install it via:

Copied!
   npm install elasticemail/elasticemail-js --save

For browser

The library also works in the browser environment via npm and browserify. After following the above steps with Node.js and installing browserify with npm install -g browserify, perform the following (assuming main.js is your entry file):

Copied!
browserify main.js > bundle.js

Then include bundle.js in the HTML pages.

Webpack Configuration

Using Webpack you may encounter the following error: "Module not found: Error: Cannot resolve module", most certainly you should disable AMD loader. Add/merge the following section to your webpack config:

Copied!
module: {
  rules: [
    {
      parser: {
        amd: false
      }
    }
  ]
}

Please follow the installation instruction and execute the following JS code:

Copied!
var ElasticEmail = require('@elasticemail/elasticemail-client');

var defaultClient = ElasticEmail.ApiClient.instance;
// Configure API key authorization: apikey
var apikey = defaultClient.authentications['apikey'];
apikey.apiKey = "YOUR API KEY"
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//apikey.apiKeyPrefix['X-ElasticEmail-ApiKey'] = "Token"

var api = new ElasticEmail.CampaignsApi()
var name = "name_example"; // {String} Name of Campaign to delete
var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully.');
  }
};
api.campaignsByNameDelete(name, callback);

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 Javascript 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!
let ElasticEmail = require('@elasticemail/elasticemail-client');
 
let defaultClient = ElasticEmail.ApiClient.instance;
 
let apikey = defaultClient.authentications['apikey'];
apikey.apiKey = "895A382DF3DCC13A97E72EXAMPLEKEY"
 
let api = new ElasticEmail.EmailsApi()
 
let email = ElasticEmail.EmailMessageData.constructFromObject({
  Recipients: [
    new ElasticEmail.EmailRecipient("MeowWow ")
  ],
  Content: {
    Body: [
      ElasticEmail.BodyPart.constructFromObject({
        ContentType: "HTML",
        Content: "My test email content ;)"
      })
    ],
    Subject: "JS EE lib test",
    From: "MyEmail "
  }
});
 
var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully.');
  }
};
api.emailsPost(email, callback);

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 Javascript library.

Add Contacts

To add contacts to your account, you will need Access Level: ModifyContacts.

Put the following code into your file.

Load library using the following line:

Copied!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const contactsApi = new ElasticEmail.ContactsApi();

Create an array with new contacts.

You can pass an array with up to 1000 contacts.

The Email field is mandatory, the rest is optional.

Find out more by checking our API's documentation.

Copied!
const contacts = [{
    Email: "johnsmith@domain.com",
    FirstName: "John",
    LastName: "Smith"
}];

Specify an existing list name in options, otherwise, contacts will be added to all contacts.

Copied!
const options = {
    listnames: ["New list"]
};

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Contacts added.');
    }
};

And finally, call contactsPost method from the API to add contacts:

Copied!
contactsApi.contactsPost(contacts, options, callback);

Delete contacts

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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const contactsApi = new ElasticEmail.ContactsApi();

Create an object with an array of contacts to delete.

Find out more by checking our API's documentation.

Copied!
const contacts = {
    Emails: ["johnsmith@domain.com"]
};

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Contacts deleted.');
    }
};

And finally, call contactsDeletePost method from the API to delete contacts:

Copied!
contactsApi.contactsDeletePost(contacts, callback);

Upload Contacts

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

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

Load library using the following line:

Copied!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

In this example we will load a CSV file that contains a list of contacts.

We will use built-in fs api for handling files in NodeJS.

Copied!
const fs = require('fs');

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

Copied!
const contactsApi = new ElasticEmail.ContactsApi();

Create a stream to read data from a file.

Copied!
const readStream = fs.createReadStream('./files/contacts.csv');

The simplest CSV file requires only one column Email, eg.:

Copied!
Email
john@johnsmith.com

Find out more by checking our API's documentation.

Create an options object where we will pass a file data, its encoding and optionaly a list name to which contacts should be added, otherwise contacts will be added to all contacts.

Copied!
const options = {
    listName: "New list",
    encodingName: 'utf-8',
    file: readStream,
};

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Contacts added.');
    }
};

And finally, call contactsImportPost method from the API to upload contacts:

Copied!
contactsApi.contactsImportPost(options, callback);

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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

In this example we will export contacts to a CSV file.

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

Copied!
const contactsApi = new ElasticEmail.ContactsApi();

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!
const options = {
    fileFormat: 'Csv',
    emails: ["johnsmith@domain.com"],
    fileName: 'exported.csv'
};

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message and link to a file.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Contacts exported');
        console.log('Link', data.Link);
    }
};

And finally, call contactsExportPost method from the API to export contacts:

Copied!
contactsApi.contactsExportPost(options, callback);

Managing Lists

In this section, we will walk you through managing your contact list on your account using the Javascript 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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const listsApi = new ElasticEmail.ListsApi();

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!
const listData = {
    ListName: "Best contacts",
    AllowUnsubscribe: true,
    Emails: ["johnsmith@domain.com"]
};

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will displaya success message.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('List added.');
    }
};

And finally, call listsPost method from the API to create a list:

Copied!
listsApi.listsPost(listData, callback);

Load List

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

Put the following code into your file. 

Load library using the following line:

Copied!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const listsApi = new ElasticEmail.ListsApi();

The only thing needed is a list name.

Find out more by checking our API's documentation.

Copied!
const listName = 'Best contacts';

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message and ListName and PublicListID. Other fields returned are: DateAdded and AllowUnsubscribe.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('List loaded', data.ListName);
        console.log('PublicListID', data.PublicListID);
    }
};

And finally, call listsByNameGet method from the API to load list details:

Copied!
listsApi.listsByNameGet(listName, callback);

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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const listsApi = new ElasticEmail.ListsApi();

The only thing needed is a list name.

Find out more by checking our API's documentation.

Copied!
const listName = 'Best contacts';

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('List deleted');
    }
};

And finally, call listsByNameDelete method from the API to delete a list:

Copied!
listsApi.listsByNameDelete(listName, callback);

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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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!
const template = {
    Name: 'My new template',
    Subject: 'Default subject',
    Body: [{
        ContentType: 'HTML',
        Charset: 'utf-8',
        Content: 'My template'
    }],
    TemplateScope: 'Personal',
};

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message and name and template type of newly created template.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Template name', data.Name);
        console.log('Template type', data.TemplateType);
    }
};

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

Copied!
templatesApi.templatesPost(template, callback);

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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

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

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

Find out more by checking our API's documentation.

Copied!
const templateName = "hello_template";

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message and name and template type of a template.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Template name', data.Name);
        console.log('Template type', data.TemplateType);
    }
};

And finally, call templatesByNameGet method from the API to load a template:

Copied!
templatesApi.templatesByNameGet(templateName, callback);

Delete Template

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

Put the following code into your file.

Load library using the following line:

Copied!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

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

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

Find out more by checking our API's documentation.

Copied!
const templateName = "hello_template";

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message and name and template type of a template.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Template deleted.');
    }
};

And finally, call templatesByNameDelete method from the API to delete a template:

Copied!
templatesApi.templatesByNameDelete(templateName, callback);

Sending Emails

In this section, we will tell you how you can start sending emails using the Javascript 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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

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

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!
const emailData = {
    Recipients: {
        To: ["johnsmith@domain.com"]
    },
    Content: {
        Body: [
            {
                ContentType: "HTML",
                Charset: "utf-8",
                Content: "Mail content."
            },
            {
                ContentType: "PlainText",
                Charset: "utf-8",
                Content: "Mail content."
            }
        ],
        From: "myemail@domain.com",
        Subject: "Example transactional email"
    }
};) 

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Email sent.');
    }
};

And finally, call emailsTransactionalPost method from the API to send an email:

Copied!
emailsApi.emailsTransactionalPost(emailData, callback);

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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const emailsApi = new ElasticEmail.EmailsApi();

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!
const emailData = {
    Recipients: [
        {
            Email: "johnsmith@domain.com",
            Fields: {
                name: "John"
            }
        }
    ],
    Content: {
        Body: [
            {
                ContentType: "HTML",
                Charset: "utf-8",
                Content: "Hi {name}!"
            },
            {
                ContentType: "PlainText",
                Charset: "utf-8",
                Content: "Hi {name}!"
            }
        ],
        From: "myemail@domain.com",
        Subject: "Example email"
    }
};

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Email sent.');
    }
};

And finally, call emailsPost method from the API to send an email:

Copied!
emailsApi.emailsPost(emailData, callback);

Managing Campaigns

Add Campaign

To add your first campaign using the Javascript 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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const campaignsApi = new ElasticEmail.CampaignsApi()

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.

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

Copied!
const campaign = {
    Name: 'hello campaign',
    Recipients: {
        ListNames: ["my list name"],
        SegmentNames: null,
    },
    Content: [{
        From: 'myemail@domain.com',
        ReplyTo: 'myemail@domain.com',
        TemplateName: "hello_template",
        Subject: 'Hello'
    }],
    Status: "Draft"
};

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message and chosen details about newly created campaign.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Campaign name', data.Name);
        console.log('Campaign status', data.Status);
    }
};

And finally, call campaignsPost method from the API to create a campaign:

Copied!
campaignsApi.campaignsPost(campaign, callback);

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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const campaignsApi = new ElasticEmail.CampaignsApi()

The only thing you need to specify is a campaign name

Find out more by checking our API's documentation.

Copied!
const campaignName = "example";

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Campaign deleted.');
    }
};

And finally, call campaignsByNameDelete method from the API to delete a campaign:

Copied!
campaignsApi.campaignsByNameDelete(campaignName, callback);

Load Campaign

To load details about an existing campaign in your account using the Javascript 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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const campaignsApi = new ElasticEmail.CampaignsApi()

The only thing you need to specify is a campaign name

Find out more by checking our API's documentation. 

Copied!
const campaignName = "example";

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message and name and status of given campaign.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Campaign name', data.Name);
        console.log('Campaign status', data.Status);
    }
};

And finally, call campaignsByNameGet method from the API to get a campaign:

Copied!
campaignsApi.campaignsByNameGet(campaignName, callback);

Update Campaign

To update existing campaigns in your account using the Javascript 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 update a campaign, put the following code into your file.

Load library using the following line:

Copied!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
configuration = ElasticEmail.Configuration()
configuration.api_key['apikey'] = 'YOUR_API_KEY'

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

Copied!
const campaignsApi = new ElasticEmail.CampaignsApi()

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
  • Conent: define your message details
  • Status: define status in which campaign should be created

Find out more by checking our API's documentation. 

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

Copied!
const campaign = {
    Name: 'hello campaign updated',
    Recipients: {
        ListNames: ["my list name"],
        SegmentNames: null,
    },
    Content: [{
        From: 'myemail@domain.com',
        ReplyTo: 'myemail@domain.com',
        TemplateName: "hello_template",
        Subject: 'Thanks for Subscribing'
    }],
    Status: "Draft"
};

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message and details from the updated version.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log('Campaign name', data.Name);
        console.log('Campaign status', data.Status);
    }
};

And finally, call campaignsByNamePut method from the API to update a campaign:

Copied!
campaignsApi.campaignsByNamePut(campaignName, campaign, callback);

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 Javascript 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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const statisticsApi = new ElasticEmail.StatisticsApi();

First, you need to specify a date range:

  • from date
  • to date – optional

Find out more by checking our API's documentation. 

Copied!
const fromDate = new Date('2022-01-17').toJSON();
const toDate = new Date('2022-04-17').toJSON();
const options = {
    to: toDate
};

Create a callback function that will be called when the response comes back.

In case of error it will display error details, otherwise it will display a success message and stringified data.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        console.log(JSON.stringify(data));
    }
};

And finally, call statisticsGet method from the API to fetch statistics:

Copied!
statisticsApi.statisticsGet(fromDate, options, callback); 

Load Channels 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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const statisticsApi = new ElasticEmail.StatisticsApi();

Channels statistics reponse is paginated you need to specfiy pagination options:

  • limit – maximum returned items, limit = 0 means to return everything till the end of the list
  • offset – how many items should be skipped from begging

Eg. to return second page of elements paginated 20 elements per page specify pagination options as follows

Copied!
    limit = 20
    offset = 20

Find out more by checking our API's documentation.

Let's fetch first 100 channels:

Copied!
{
    limit: 20,
    offset: 0,
};

Let's fetch everthing:

Copied!
const pageinationOptions = {
    limit: 0,
    offset: 0,
};

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message and stringified data for each channel.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        data.forEach((channel) => {
            console.log(JSON.stringify(channel));
        });
    }
};

And finally, call statisticsChannelsGet method from the API to fetch statistics:

Copied!
statisticsApi.statisticsChannelsGet(pageinationOptions, callback);

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!
const ElasticEmail = require('@elasticemail/elasticemail-client');

Get client instance:

Copied!
const client = ElasticEmail.ApiClient.instance;

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

Copied!
const apikey = client.authentications['apikey'];
apikey.apiKey = "YOUR_API_KEY";

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

Copied!
const statisticsApi = new ElasticEmail.StatisticsApi();

Campaigns statistics reponse is paginated you need to specfiy pagination options:

  • limit – maximum returned items, limit = 0 means to return everything till the end of the list
  • offset – how many items should be skipped from begging

Eg. to return second page of elements paginated 20 elements per page specify pagination options as follows

Copied!
{
    limit: 20,
    offset: 0,
};

Find out more by checking our API's documentation.

Let's fetch everthing:

Copied!
const pageinationOptions = {
    limit: 0,
    offset: 0,
};

Create a callback function that will be called when response comes back.

In case of error it will display error details, otherwise it will display a success message and stringified data for each campaign.

Copied!
const callback = (error, data, response) => {
    if (error) {
        console.error(error);
    } else {
        console.log('API called successfully.');
        data.forEach((campaign) => {
            console.log(JSON.stringify(campaign));
        });
    }
};

And finally, call statisticsCampaignsGet method from the API to fetch statistics:

Copied!
statisticsApi.statisticsCampaignsGet(pageinationOptions, callback);
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.

Instant setup No credit card required