Libraries

Python

Elastic Email Python 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 Python library. You can find our whole downloadable Python 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

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

The required Python version is 3.6 or later.

Installation

Our official downloadable Python library is available on GitHub.

We’ve prepared for you the steps to take to install and implement our Python library:
If the python package is hosted on a repository, you can install it directly using:

Copied!
pip install git+https://github.com/elasticemail/elasticemail-python.git

(you may need to run pip with root permission: sudo pip install

git+https://github.com/elasticemail/elasticemail-python.git)

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 Python 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!
configuration = ElasticEmail.Configuration()
configuration.api_key['apikey'] = '895A382DF3DCC13A97E72EXAMPLEKEY'
 
with ElasticEmail.ApiClient(configuration) as api_client:
    api_instance = emails_api.EmailsApi(api_client)
    email_message_data = EmailMessageData(
        recipients=[
            EmailRecipient(
                email="MeowWow "
            ),
        ],
        content={
	    "Body": [
		{
		    "ContentType":"HTML",
		    "Content":"My test email content ;)"
		}
	    ],
	    "Subject": "Python EE lib test",
	    "From": "MyEmail "
	}
    )
 
    try:
        api_response = api_instance.emails_post(email_message_data)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling EmailsApi->emails_post: %s\n" % e)

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 Python 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!
import ElasticEmail
from ElasticEmail.api import contacts_api
from ElasticEmail.model.contact_status import ContactStatus
from ElasticEmail.model.contact_payload import ContactPayload
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an API client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
api_instance = contacts_api.ContactsApi(api_client)

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!
   contact_payload = [
        ContactPayload(
            email="johnsmith@domain.com",
            status=ContactStatus("Active"),
            first_name="John",
            last_name="Smith",
        ),
    ]

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

Copied!
  list_names = [
        "New list",
    ]

Use try & except block to call contacts_post method from the API to add contacts:

Copied!
     try:
        api_response = api_instance.contacts_post(contact_payload, listnames=list_names)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling ContactsApi->contacts_post: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import contacts_api
from ElasticEmail.model.emails_payload import EmailsPayload

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an API client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
   api_instance = contacts_api.ContactsApi(api_client)

Create an object with an array of contacts to delete.

Find out more by checking our API's documentation.

Copied!
   emails_payload = EmailsPayload(
        emails=["johnsmith@domain.com"],
    )

Use try & except block to call contacts_delete_post method from the API to delete contacts:

Copied!
        api_instance.contacts_delete_post(emails_payload)
    try:
        print("Contacts deleted.")
    except ElasticEmail.ApiException as e:
        print("Exception when calling ContactsApi->contacts_delete_post: %s\n" % e)

Upload Contacts

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

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

Load library using the following line:

Copied!
import ElasticEmail
from ElasticEmail.api import contacts_api

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an API client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
   api_instance = contacts_api.ContactsApi(api_client)

Create options

  • file encoding
  • optionally, a list name to which contacts should be added, otherwise contacts will be added to all contacts.
Copied!
   list_name = "Best contacts"
    encoding_name = "utf-8"

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

Copied!
Email
john@johnsmith.com

Find out more by checking our API's documentation.

Load file

Copied!
file = open('./files/contacts.csv', 'rb')

Use try & except block to call contacts_import_post method from the API to upload contacts:

Copied!
api_instance.contacts_import_post(list_name=list_name, encoding_name=encoding_name, file=file)
    try:
        print("Contacts uploaded.")
    except ElasticEmail.ApiException as e:
        print("Exception when calling ContactsApi->contacts_import_post: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import contacts_api
from ElasticEmail.model.export_file_formats import ExportFileFormats
from ElasticEmail.model.compression_format import CompressionFormat
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an API client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

Create an instance of ContactsApi that will be used to create a file with exported contacts.

Copied!
   api_instance = contacts_api.ContactsApi(api_client)

Create options variables:

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

Other options:

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

Find out more by checking our API's documentation.

Copied!
   file_format = ExportFileFormats("Csv")
    emails = [
        "johnsmith@domain.com",
    ]
    compression_format = CompressionFormat("None")
    file_name = "exported.csv"

Use try & except block to call contacts_export_post method from the API to export contacts:

Copied!
        api_response = api_instance.contacts_export_post(file_format=file_format, emails=emails, compression_format=compression_format, file_name=file_name)
    try:
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling ContactsApi->contacts_export_post: %s\n" % e)

Managing Lists

In this section, we will walk you through managing your contact list on your account using the Python 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!
import ElasticEmail
from ElasticEmail.api import lists_api
from ElasticEmail.model.list_payload import ListPayload
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an API client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
   api_instance = lists_api.ListsApi(api_client)

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 = ListPayload(
        list_name="Best contacts",
        allow_unsubscribe=True,
        emails=[
            "johnsmith@domain.com",
        ],
    )

Use try & except block to call lists_post method from the API to create a list:

Copied!
    try:
        api_response = api_instance.lists_post(list_payload)
        pprint(api_response)

    except ElasticEmail.ApiException as e:

Copied!
        print("Exception when calling ListsApi->lists_post: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import lists_api
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an API client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
   api_instance = lists_api.ListsApi(api_client)

The only thing needed is a list name.

Find out more by checking our API's documentation.

Copied!
   name = "Best contacts"

Use try & except block to call lists_by_name_get method from the API to fetch a list:

Copied!
        api_response = api_instance.lists_by_name_get(name)
    try:
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling ListsApi->lists_by_name_get: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import lists_api

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an API client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
   api_instance = lists_api.ListsApi(api_client)

The only thing needed is a list name.

Find out more by checking our API's documentation.

Copied!
   name = "Best contacts"

Use try & except block to call lists_by_name_delete method from the API to delete a list:

Copied!
        api_instance.lists_by_name_delete(name)
    try:
        print("List deleted.")
    except ElasticEmail.ApiException as e:
        print("Exception when calling ListsApi->lists_by_name_delete: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import templates_api
from ElasticEmail.model.body_part import BodyPart
from ElasticEmail.model.body_content_type import BodyContentType
from ElasticEmail.model.template_payload import TemplatePayload
from ElasticEmail.model.template_scope import TemplateScope
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
    api_instance = templates_api.TemplatesApi(api_client)

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 = TemplatePayload(
        name="My new template",
        subject="Default subject",
        body=[
            BodyPart(
                content_type=BodyContentType("HTML"),
                content="My template",
                charset="utf-8",
            ),
        ],
        template_scope=TemplateScope("Personal"),
    )

Use try & except block to call templates_post method from the API to create a template:

Copied!
    try:
        api_response = api_instance.templates_post(template_payload)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling TemplatesApi->templates_post: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import templates_api
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

Create an instance of TemplatesApi that will be used to load existing template on your account.

Copied!
    api_instance = templates_api.TemplatesApi(api_client)

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

Find out more by checking our API's documentation.

Copied!
    template_payload = TemplatePayload(
        name="My new template",
        subject="Default subject",
        body=[
            BodyPart(
                content_type=BodyContentType("HTML"),
                content="My template",
                charset="utf-8",
            ),
        ],
        template_scope=TemplateScope("Personal"),
    )

Use try & except block to call templates_by_name_get method from the API to load a template:

Copied!
    try:
        api_response = api_instance.templates_by_name_get(name)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling TemplatesApi->templates_by_name_get: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import templates_api


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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

Create an instance of TemplatesApi that will be used to delete existing template from your account.

Copied!
    api_instance = templates_api.TemplatesApi(api_client)

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

Find out more by checking our API's documentation.

Copied!
    name = "My template"

Use try & except block to call templates_by_name_delete method from the API to delete a template:

Copied!
    try:
        api_instance.templates_by_name_delete(name)
        print("Template deleted.")
    except ElasticEmail.ApiException as e:
        print("Exception when calling TemplatesApi->templates_by_name_delete: %s\n" % e)

Sending Emails

In this section, we will tell you how you can start sending emails using the Python 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!
import ElasticEmail
from ElasticEmail.api import emails_api
from ElasticEmail.model.email_content import EmailContent
from ElasticEmail.model.body_part import BodyPart
from ElasticEmail.model.body_content_type import BodyContentType
from ElasticEmail.model.transactional_recipient import TransactionalRecipient
from ElasticEmail.model.email_transactional_message_data import EmailTransactionalMessageData
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
    api_instance = emails_api.EmailsApi(api_client)

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_transactional_message_data = EmailTransactionalMessageData(
        recipients=TransactionalRecipient(
            to=[
                "johnsmith@domain.com",
            ],
        ),
        content=EmailContent(
            body=[
                BodyPart(
                    content_type=BodyContentType("HTML"),
                    content="Mail content.",
                    charset="utf-8",
                ),
                BodyPart(
                    content_type=BodyContentType("PlainText"),
                    content="Mail content.",
                    charset="utf-8",
                ),
            ],
            _from="myemail@domain.com",
            reply_to="myemail@domain.com",
            subject="Example transactional email",
        ),
    ) 

Use try & except block to call emails_transactional_post method from the API to send an email:

Copied!
    try:
        api_response = api_instance.emails_transactional_post(email_transactional_message_data)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling EmailsApi->emails_transactional_post: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import emails_api
from ElasticEmail.model.email_content import EmailContent
from ElasticEmail.model.body_part import BodyPart
from ElasticEmail.model.body_content_type import BodyContentType
from ElasticEmail.model.email_recipient import EmailRecipient
from ElasticEmail.model.email_message_data import EmailMessageData
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
    api_instance = emails_api.EmailsApi(api_client)

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 = EmailMessageData(
        recipients=[
            EmailRecipient(
                email="johnsmith@domain.com",
                fields={
                    "name": "John",
                },
            ),
        ],
        content=EmailContent(
            body=[
                BodyPart(
                    content_type=BodyContentType("HTML"),
                    content="Hi {name}!",
                    charset="utf-8",
                ),
                BodyPart(
                    content_type=BodyContentType("PlainText"),
                    content="Hi {name}!",
                    charset="utf-8",
                ),
            ],
            _from="myemail@domain.com",
            reply_to="myemail@domain.com",
            subject="Example email",
        ),
    )

Use try & except block to call emails_post method from the API to send an email:

Copied!
    try:
        api_response = api_instance.emails_post(email_message_data)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling EmailsApi->emails_post: %s\n" % e)

Managing Campaigns

Add Campaign

To add your first campaign using the Python 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!
import ElasticEmail
from ElasticEmail.api import campaigns_api
from ElasticEmail.model.campaign import Campaign
from ElasticEmail.model.campaign_recipient import CampaignRecipient
from ElasticEmail.model.campaign_status import CampaignStatus
from ElasticEmail.model.campaign_template import CampaignTemplate
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
    api_instance = campaigns_api.CampaignsApi(api_client)

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!
    campaign = Campaign(
        content=[
            CampaignTemplate(
                _from="karol.szczycinski@elasticemail.com",
                reply_to="karol.szczycinski@elasticemail.com",
                subject="Hello",
                template_name="hello_template",
            ),
        ],
        name="hello campaign",
        status=CampaignStatus("Draft"),
        recipients=CampaignRecipient(
            list_names=[
                "my list name",
            ],
        ),
    )

Use try & except block to call campaigns_post method from the API to create a campaign:

Copied!
    try:
        api_response = api_instance.campaigns_post(campaign)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling CampaignsApi->campaigns_post: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import campaigns_api

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
    api_instance = campaigns_api.CampaignsApi(api_client)

The only thing you need to specify is a campaign name

Find out more by checking our API's documentation.

Copied!
    name = "hello campaign"

Use try & except block to call campaigns_by_name_delete method from the API to delete a campaign:

Copied!
    try:
        api_instance.campaigns_by_name_delete(name)
        print("Campaign deleted.")
    except ElasticEmail.ApiException as e:
        print("Exception when calling CampaignsApi->campaigns_by_name_delete: %s\n" % e)

Load Campaign

To load details about an existing campaign in your account using the py 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!
import ElasticEmail
from ElasticEmail.api import campaigns_api
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
   api_instance = campaigns_api.CampaignsApi(api_client)

The only thing you need to specify is a campaign name

Find out more by checking our API's documentation. 

Copied!
    name = "hello campaign"

Use try & except block to call campaigns_by_name_get method from the API to fetch campaign details:

Copied!
    try:
        api_response = api_instance.campaigns_by_name_get(name)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling CampaignsApi->campaigns_by_name_get: %s\n" % e)

Update Campaign

To update existing campaigns in your account using the Python 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!
import ElasticEmail
from ElasticEmail.api import campaigns_api
from ElasticEmail.model.campaign import Campaign
from ElasticEmail.model.campaign_recipient import CampaignRecipient
from ElasticEmail.model.campaign_status import CampaignStatus
from ElasticEmail.model.campaign_template import CampaignTemplate
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
    api_instance = campaigns_api.CampaignsApi(api_client)

Create an example campaign object:

  • 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!
    campaign = Campaign(
        content=[
            CampaignTemplate(
                _from="karol.szczycinski@elasticemail.com",
                reply_to="karol.szczycinski@elasticemail.com",
                subject="Hello",
                template_name="hello_template",
            ),
        ],
        name="hello campaign update",
        status=CampaignStatus("Draft"),
        recipients=CampaignRecipient(
            list_names=[
                "my list name",
            ],
        ),
    )

Use try & except block to call campaigns_by_name_put method from the API to update a campaign:

Copied!
    try:
        api_response = api_instance.campaigns_by_name_put(name, campaign)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling CampaignsApi->campaigns_by_name_put: %s\n" % e)

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 Python 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!
from datetime import datetime
import ElasticEmail
from ElasticEmail.api import statistics_api
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:


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

Copied!
    api_instance = statistics_api.StatisticsApi(api_client)

First, you need to specify a date range:

  • from date
  • to date – optional

Find out more by checking our API's documentation. 

Copied!
    _from = datetime(2022,1,1,00,00,00)
    to = datetime(2022,1,30,00,00,00)

Use try & except block to call statistics_get method from the API to load a statistics with only from date given:

Copied!
    try:
        api_response = api_instance.statistics_get(_from)
        print("From %s" % _from)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling StatisticsApi->statistics_get: %s\n" % e)
Copied!
    try:
        api_response = api_instance.statistics_get(_from, to=to)
        print(f"\nFrom {_from} To {to}")
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling StatisticsApi->statistics_get: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import statistics_api
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
    api_instance = statistics_api.StatisticsApi(api_client)

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 = 100
    offset = 0 

Use try & except block to call statistics_channels_get method from the API to fetch statistics:

Copied!
    try:
        api_response = api_instance.statistics_channels_get(limit=limit, offset=offset)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling StatisticsApi->statistics_campaigns_get: %s\n" % e)

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!
import ElasticEmail
from ElasticEmail.api import statistics_api
from pprint import pprint

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

Defining the host is optional and defaults to https://api.elasticemail.com/v4

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

Pass configuration to an api client and make it instance available under api_client name:

Copied!
with ElasticEmail.ApiClient(configuration) as api_client:

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

Copied!
    api_instance = statistics_api.StatisticsApi(api_client)

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 = 20

Find out more by checking our API's documentation.

Let's fetch first 100 campaigns:

Copied!
    limit = 100
    offset = 0 

Use try & except block to call statistics_campaigns_get method from the API to fetch statistics:

Copied!
    try:
        api_response = api_instance.statistics_campaigns_get(limit=limit, offset=offset)
        pprint(api_response)
    except ElasticEmail.ApiException as e:
        print("Exception when calling StatisticsApi->statistics_campaigns_get: %s\n" % e)
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.

Free 100 emails/day No credit card required