Introduction to the Moosend API

Abstract

Introduction to the Moosend API and what topics are included in this API documentation.

Moosend is a cloud-based, AI-powered email marketing solution that allows you to target your audience at scale.

The API enables you to connect directly to the Moosend infrastructure and programmatically run many of the system’s capabilities from creating email lists to retrieving advanced real-time analytics in an easier, faster, and more efficient manner.

To get started, you need a Moosend  account and an API key. By accessing the API endpoints, you can programmatically leverage the system’s core capabilities:

Email lists

  • Create, retrieve, update, or delete email lists and their details.

  • Create or update custom data included in the email lists.

Subscribers

  • Add up to 1000 subscribers with their custom data or retrieve them by ID or email address.

  • Remove subscribers or unsubscribe them from an email list or a campaign.

Campaigns

  • Create or clone campaigns, and efficiently retrieve their details and campaign senders.

  • Send a test campaign, schedule campaign delivery, or dispatch it immediately.

  • Retrieve campaign metrics such as link performance, opens, clicks, and A/B test results to make data-driven decisions.

Segments

  • Create, update, delete, and retrieve segments with their details and subscribers.

Getting started with the Moosend API

Abstract

Overview of how to get started with the Moosend API.

Before you can start using the Moosend API, you must have a Moosend account. Each account is associated with a specific role, such as Owner, Admin, Viewer, Manager, Designer, Admin observer, and GDPR viewer. The permissions specific to your role determine which resources and endpoints you can access with your API key.

Base URL

Abstract

Describes the base URL for all Moosend API endpoints.

All API request URLs referenced in this API documentation begin with the following base URL:

https://api.moosend.com/v3

The base URL includes the {hostname} which is api.moosend.com and the API version v3.

To make a request to a specific API endpoint, the path to the endpoint is added to the base URL.

For example, to make a request to get all active email lists in your account, create a GET request and add the specific endpoint path /lists to the base URL:

https://api.moosend.com/v3/lists

Authenticate a Moosend API request

Abstract

Overview of the authentication process and how to get your API key from your Moosend account.

All Moosend API requests are authenticated by providing your API key. Moosend provides your account with a unique key that can be found in your settings.

To get your API key:

  1. Log in to your account.

  2. On the menu bar, click More > Settings.

  3. Click API key.

  4. To copy your API key, click Copy.

    Important

    You must keep your API key secure to prevent any unauthorized access to your account. You can click Generate new API key to create a new API key if your account gets compromised.

When you obtain your API key, you can begin making calls to the Moosend API. The API key is a required query parameter in all API endpoints.

For example, if your API key is bafe55f4-e53e-4651-8164-c6d6ff05081b, then a sample request to get all campaigns looks like the following:

curl --include \
'https://{hostname}/v3/campaigns.{Format}?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b'

HTTP methods

Abstract

Describes the standard HTTP methods to use when making calls to the Moosend APIs.

The Moosend API uses the following standard HTTP methods for indicating the action to take on available resources:

  • GET - you can use this method to retrieve data from your account in our system. When you make a GET request, all request parameters are added to the request URL, in a format specific to the API call.

    curl --include \
    'https://{hostname}/v3/campaigns.{Format}?apikey='
  • DELETE - you can use this method to remove information from your account.

    curl --include \
         --request DELETE \
    'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey='
  • POST - you can use this method to send data to our system to modify data in your account. When you make a POST request, the request URL usually contains the response format and authentication, and the request stream contains hypothetical parameters for Name, Subject, SenderEmail, WebLocation, and MailingListID:

    curl --include \
         --request POST \
         --header "Content-Type: application/json" \
         --header "Accept: application/json" \
         --data-binary "{
        \"Name\":\"Test campaign\",
        \"Subject\":\"Some subject\",
        \"SenderEmail\":\"something@email.com\",
        \"ReplyToEmail\":\"something@email.com\",
        \"ConfirmationToEmail\":\"something@email.com\",
        \"HTMLContent\":\"Some HTML body\",      
        \"MailingLists\": [
            {
                \"MailingListID\":\"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
                \"SegmentID\":\"10166\"
            },
            {
                \"MailingListID\":\"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
            }
        ],
        \"IsAB\":\"true\",
        \"ABCampaignType\":\"Content\",
        \"WebLocationB\":\"http://www.mysite.gr/newsletter/index\",
        \"HoursToTest\":\"2\",
        \"ListPercentage\":\"20\",
        \"ABWinnerSelectionType\":\"OpenRate\"
    }" \
    'https://{hostname}/v3/campaigns/create.{Format}?apikey='
    

Request and response parameters

Abstract

Describes the different types of request and response parameters that are used when making calls to the Moosend API.

When making an API request, you can pass different parameters to the API endpoints to determine the response. There are several types of request parameters: header parameters, path parameters, query parameters, and request body parameters.

Not all Moosend API endpoints contain each type of parameter. The API Reference details the specific request and response parameters for each API endpoint.

Header parameters

You must set the correct header parameters in every API request to retrieve the response data in the expected format and data type. The following headers are supported in Moosend API requests:

Request header

Value

Accept

application/json

application/xml

application/html+xml

Content-Type

application/json

For the response header parameter, only the JSON type is supported.

Request header

Value

Accept

application/json

Content-Type

application/json

Query parameters

You can use query parameters for filtering, pagination, and partial responses in the Moosend API. Query parameters are added to the request URL after the query string ?. You can add one or more query parameters separated by &.

The following is an example that shows three query parameters apikey, WithStatistics, and SortMethod.

curl --include \
'https://{hostname}/v3/lists.{Format}?apikey=value1&&WithStatitiscs=value2&SortMethod=value3'

When you have an API request that uses query parameters, you must add the actual value of each parameter after the =. For example:

curl --include \
'https://{hostname}/v3/campaigns.{Format}?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b'

The apikey is an example of a request query parameter that is required in all Moosend API endpoints.

Path parameters

You can use path parameters as identifiers to help you structure your requests. Path parameters appear within the path of the request URL before the query string ? and are usually indicated in curly brackets { }.

The following example shows three path parameters Page, PageSize, and Format:

curl --include \
'https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?'

When you have an API request that uses path parameters, you must replace the path parameter with their actual values in your request. For example:

curl --include \
'https://{hostname}/v3/lists/1/100.json?'

Format is an example of a path parameter that is required in all Moosend API endpoints. There are only two available formats you can use in getting a response: xml and json.

Request body parameters

For POST requests, you must include a request body with parameters. You can find the details of request body parameters for each endpoint, including required fields in the API Reference.

The following is an example of a request body containing the Name, ConfirmationPage, and RedirectAfterUnsubscribePage parameters:

curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"New List\",
    \"ConfirmationPage\":\"www.someUrl.com\",
    \"RedirectAfterUnsubscribePage\":\"www.someUrl.com\"
}" \
'https://{hostname}/v3/lists/create.{Format}?apikey='

Response body parameters

All responses to API calls include an HTTP status code, a response header, and a response schema with a JSON-formatted body. You can find the details of the response body parameters corresponding to each endpoint in the API Reference.

The following is an example of a JSON response body containing three parameters for Code, Error, and Context:

{
  "Code": 0,
  "Error": null,
  "Context": "e5f6c0a3-1fe6-4d89-951e-eafae0b01368"
}

HTTP status codes

Abstract

Describes the possible HTTP status codes returned in the Moosend API response.

The Moosend API returns standard HTTP success or error status codes. The following is a list of various HTTP status codes that the API returns:

HTTP status code

Description

200 OK

The request was successful.

201 Created

The request has been fulfilled and has resulted in one or more new resources being created.

202 Accepted

The request has been accepted for processing, but the processing has not been completed.

400 Bad Request

The server cannot process the request due to something that is perceived to be a client error.

API rate limiting

Abstract

Describes the API rate limiting enforced by Moosend to prevent having too many requests.

The Moosend API enforces rate limiting to prevent the API from being overwhelmed by too many requests. This means that it allows only a certain number of API calls from users within a given time. If a user sends too many requests, API rate limiting can throttle client connections.

The following table describes the current rate limit (number of requests per 10 seconds) per user (per API key):

Resource

Method

Endpoint path

Rate limit

Add subscribers

POST

/subscribers/{MailingListID}/subscribe.{Format}

10

Add multiple subscribers

POST

/subscribers/{MailingListID}/subscribe_many.{Format}

2

Unsubscribe a subscriber from an account

POST

/subscribers/unsubscribe.{Format}

20

Unsubscribe a subscriber from an email list

POST

/subscribers/{MailingListID}/unsubscribe.{Format}

20

Unsubscribe a subscriber from an email list and a campaign

POST

/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}

20

Example response

The following is an example of a response when request submissions exceed the rate limit. When you go over the rate limit, you receive a RATE_LIMITING error in the response body.

{
  "Code": 429,
  "Error": "RATE_LIMITING",
  "Context": null
}

Walkthrough: Create a mailing list and add subscribers

Abstract

Provides a walkthrough in making your first requests to the Moosend API to create a new email list and add multiple subscribers to the list.

This walkthrough shows how you can make your first calls to the Moosend API. When making API requests, you must always locate the specific API endpoints and parameters you need in API reference.

In this example, you create two requests using two API endpoints.

This walkthrough describes how to:

Create a new email list using the API

To create a new email list using the API:

  1. Go to the Create a mailing list endpoint reference.

  2. Create a POST request using /lists/create.{Format}.

  3. Add your request header. You can use the following value: Content-Type:application/json.

  4. Add the required Format in the request URL path. Possible values are json or xml.

    For example, if you select a JSON format, you can edit the URL as: https://{hostname}/v3/lists/create.json.

  5. Add the required apikey parameter in the request URL after the ?.

    For example, you can add your API key as https://{hostname}/v3/lists/create.json?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b.

  6. Add the required request body parameter for Name. Optionally, you can add the ConfirmationPage, and RedirectAfterUnsubscribePage parameters.

    curl --include \
         --request POST \
         --header "Content-Type: application/json" \
         --header "Accept: application/json" \
         --data-binary "{
        \"Name\":\"New List\",
        \"ConfirmationPage\":\"www.someUrl.com\",
        \"RedirectAfterUnsubscribePage\":\"www.someUrl.com\"
    }" \
    'https://{hostname}/v3/lists/create.json?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b'
    
    
  7. Send your API request. If successful, you get a response with HTTP code 200, a Content-Type: application/json response header, and the following JSON response:

    {
      "Code": 0,
      "Error": null,
      "Context": "6ca52d31-765c-4760-a78e-91e511e49d76"
    }

    The response body contains the Context parameter that gives you the ID of the new email list created. You can now use this ID to add subscribers to your new email list using the next API endpoint.

Add subscribers to your new email list using the API

To add subscribers to your new email list:

  1. Go to the Add multiple subscribers endpoint reference.

  2. Create a POST request using /subscribers/{MailingListID}/subscribe_many.{Format}.

  3. Add your request header. You can use the following value: Content-Type:application/json.

  4. Add the required path parameters in the request URL. Possible values for Format are json or xml. For MailingListID, use the ID of the new email list you created.

    For example, if you select a JSON format and use the new email list ID, you can edit the URL as:

    https://{hostname}/v3/subscribers/6ca52d31-765c-4760-a78e-91e511e49d76/subscribe_many.json

  5. Add the required query parameter in the request URL after the ?.

    For example, you can add your API key as https://{hostname}/v3/subscribers/6ca52d31-765c-4760-a78e-91e511e49d76/subscribe_many.json?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b

  6. Add the required request body parameters for Subscribers. You must specify the Name, Email, and CustomEields for each subscriber on this list. Optionally, you can add the HasExternalDoubleOptIn parameter.

    curl --include \
         --request POST \
         --header "Content-Type: application/json" \
         --header "Accept: application/json" \
         --data-binary "{  
        \"HasExternalDoubleOptIn\": false,
        \"Subscribers\":[  
          {  
             \"Name\":\"test1Email\",
             \"Email\":\"test1@test.com\",
             \"CustomFields\":[  
                \"Country=UK\"
             ]
          },
          {  
             \"Name\":\"test2133Email\",
             \"Email\":\"test2133@test.com\",
             \"CustomFields\":[  
                \"Age=25\",
                \"Country=USA\"
             ]
          }
       ]
    }" \
    'https://{hostname}/v3/subscribers/6ca52d31-765c-4760-a78e-91e511e49d76/subscribe_many.json?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b'
    
  7. Send your API request. If successful, you get a response with HTTP code 200, a Content-Type: application/json response header, and the following JSON response:

    {
      "Code": 0,
      "Error": "2 items with invalid email address were ignored: email@email, email2@email",
      "Context": [
        {
          "ID": "ca506fc5-0967-4756-8848-74e9766bdbdd",
          "Name": "test1Email",
          "Email": "test1@test.com",
          "CreatedOn": "/Date(1465377493907+0100)/",
          "UpdatedOn": "/Date(1465381164389)/",
          "UnsubscribedOn": null,
          "UnsubscribedFromID": null,
          "SubscribeType": 1,
          "SubscribeMethod": 1,
          "CustomFields": [
            {
              "CustomFieldID": "42acf2cf-1096-4c80-960b-051791d9a276",
              "Name": "Country",
              "Value": "UK"
            }
          ],
          "RemovedOn": null
        },
        {
          "ID": "b751f349-f6b3-4b14-8d75-c37dfafbe40a",
          "Name": "test2133Email",
          "Email": "test2133@test.com",
          "CreatedOn": "/Date(1465377493907+0100)/",
          "UpdatedOn": "/Date(1465381164389)/",
          "UnsubscribedOn": null,
          "UnsubscribedFromID": null,
          "SubscribeType": 1,
          "SubscribeMethod": 1,
          "CustomFields": [
            {
              "CustomFieldID": "60d4e2b0-e5ae-4737-9ac5-ce071ab346fb",
              "Name": "Age",
              "Value": 25
            },
            {
              "CustomFieldID": "42acf2cf-1096-4c80-960b-051791d9a276",
              "Name": "Country",
              "Value": "USA"
            }
          ],
          "RemovedOn": null
        }
      ]
    }

    The response body contains the Context parameter that gives you the ID and details of each subscriber added to the new email list.

Introduction to segmentation

Abstract

Provides a basic description of segmentation and the query or expression used in Moosend API calls.

You can add segments to your email lists to send targeted email marketing campaigns. You can define a specific audience subset in your email lists using a segmentation query or expression to match the subscribers based on content engagement, location, language, and so on. You can have a single segmentation query or an expression consisting of multiple queries in complex or nested combinations.

A segmentation query or criterion consists of the following parts:

  • Field - the criterion used to filter the email list. See list of segmentation fields.

  • Comparer - the operator that defines how to compare a Field with its Value. Each field supports specific comparers based on the data type. See list of comparers.

  • Additional parameters:

    • MatchType - defines how to combine a group of queries or criteria. It specifies how subscribers are returned by your segment based on matching criteria. Possible values are:

      • All - returns subscribers that match all the given criteria.

      • Any - returns subscribers that match any of the given criteria.

    • FetchType -defines how many criteria-matching subscribers are contained in your segment. Possible values are:

      • All - returns all criteria-matching subscribers.

      • Top - returns only a maximum number of subscribers defined in FetchValue.

      • TopPercent - returns only a percentage of subscribers defined in FetchValue.

    • FetchValue - specifies the maximum number for FetchType:Top or percentage for FetchType:TopPercent of members to be contained in the created segment.

List of segmentation fields

Abstract

Lists the segmentation fields that are used in Moosend API segmentation expressions.

Segmentation queries or expressions can contain any combination of the Fields described in the following tables. You can use either the field name or the corresponding code in your JSON request body. Some fields accept these additional parameters:

  • Date Constrain - constrains the results based on a related date field.

  • OtherMailingListId - runs the query on another email list on members that are contained in both the current and the other email list.

  • CustomFieldId or CustomFieldName - used only with CustomField and specifies the custom field definition by the ID or the name for which the query applies. The custom field definition can be either one of the current email lists or the email list specified by the OtherMailingListId parameter.

Member fields

Code

Data type

Date constrain

OtherMailingListId

DateAdded

1

dateTime

Yes

DateUpdated

16

dateTime

Yes

RecipientName

2

string

Yes

RecipientEmail

3

string

SubscribeMethod

14

enum

Yes (SubscribedOn)

Yes

CustomField

99

string, decimal, dateTime, Boolean

Yes

MailingList

17

guid

Campaign fields

Code

Data type

Date constrain

OtherMailingListId

CampaignsOpened

4

integer

Yes (DeliveredOn)

Yes

LinksClicked

5

integer

Yes (DeliveredOn)

Yes

CampaignName

6

string

Yes (DeliveredOn)

Yes

CampaignTitle

20

string

Yes (Timestamp)

Yes

LinkURL

7

guid

Yes (DeliveredOn)

Yes

CampaignSent

15

guid

Yes (Timestamp)

Yes

OpenedAnyCampaign

24

Boolean

Yes (Timestamp)

Yes

CampaignID

19

guid

Yes (Timestamp)

Yes

SpecificCampaignClicked

26

string

Yes (Timestamp)

Yes

CampaignIdNotOpened

27

string

Yes

User agent fields

Code

Data type

Date constrain

OtherMailingListId

Platform

8

enum (Desktop = 1, Mobile = 2, Other = 3)

OperatingSystem

9

string

EmailClient

10

string

WebBrowser

11

string

MobileBrowser

12

string

Website fields

Code

Data type

Date constrain

OtherMailingListId

AddedAnythingToCart

21

Boolean + extra (CampaignId, ProductCode, WebsiteId, Times)

Yes (Timestamp)

Yes

ViewedProduct

22

Boolean + extra (CampaignId, ProductCode, WebsiteId, Times)

Yes (Timestamp)

Yes

PurchasedProduct

23

Boolean + extra (CampaignId, ProductCode, WebsiteId, Times)

Yes (Timestamp)

Yes

List of comparers

Abstract

Lists the comparers or operators that are used in Moosend API segmentation queries.

Query comparers or operators differ according to the data type of the field. The following table lists the supported operators for each data type. You can use either the name or the code in your JSON request body.

IsEmpty* and IsNotEmpty* are available when the field is nullable.

Operator

Code

String

Integer

Decimal

DateTime

Enum

Guid

Boolean

Is

0

+

+

+

+

+

+

IsNot

1

+

+

+

+

+

+

Contains

2

+

DoesNotContain

3

+

StartsWith

4

+

DoesNotStartWith

5

+

EndsWith

6

+

DoesNotEndWith

7

+

IsGreaterThan

8

+

+

IsGreaterThanOrEqualTo

9

+

+

IsLessThan

10

+

+

IsLessThanOrEqualTo

11

+

+

IsBefore

12

+

IsAfter

13

+

IsEmpty*

14

+

+

+

+

+

+

+

IsNotEmpty*

15

+

+

+

+

+

+

+

IsTrue

16

+

IsFalse

17

+

IsBetween

24

+

+

+

IsNotBetween

25

+

+

+

List of date functions

Abstract

Lists the date functions that are used in Moosend API segmentation fields.

The following table describes the DateFunction values that you can use with fields that have a DateTime data type. You can query based on a property of the date instead of the date itself. The calculation depends on the TimeZoneUsed parameter. Possible time zone values are Local or Utc. When Local is used, the user’s time zone offset is considered.

Function name

Code

Description

Year

1

The four-digit year part of the date.

Month

2

The month part of the date from 1 to 12.

Day

3

The day part of the date from 1 to 31.

WeekDay

4

The day of the week from 1 to 7. For example, 1 for Sunday, 2 for Monday, and so on.

DaysPassed

5

The number of days that have passed until now.

HoursPassed

6

The number of hours that have passed until now.

MinutesPassed

7

The number of minutes that have passed until now.

List of date constrain parameters

Abstract

Lists the date parameters that are used to constrain results of a Moosend API response based on the elapsed time or date span.

You can constrain the results of a Moosend API response based on the elapsed time or date span using the following parameters:

  • LastXMinutes - constrains the results by the time that has elapsed.

  • DateFrom and DateTo - constrain the results based on a specific date span.

API reference

The following sections provide the reference containing all the information required to work with the Moosend API endpoints:

Mailing lists

Abstract

Describes how to use the Moosend API to create, edit, and manage email lists in your account.

Use the Moosend API to get your email lists, get details about email lists, create, update, and delete email lists. You can also create, update, or remove custom fields in your email lists.

Get all active mailing lists

Abstract

Describes the request and response details of this Moosend API endpoint to get your active email lists.

Request

Parameter

In

Type

Required

Description

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

WithStatistics

query

string

false

Specifies whether to fetch statistics for the subscribers.

Possible values: true (Default) and false.

ShortBy

query

string

false

The name of the email list property to sort results by.

Possible values: Name, Subject, Status, DeliveredOn, and CreatedOn (Default).

SortMethod

query

string

false

Specifies the method to sort results.

Possible values: DESC for descending and ASC (Default) for ascending.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and MailingLists information for the requested email list:

  • Paging - an object that contains the following information:

    • PageSize - the page size of the results. This is 0 if not defined.

    • CurrentPage - the number of the result page. This is 1 if not defined.

    • Totalresults - the number of email lists that are included in the response.

    • TotalPageCount - the total number of available email list pages in your account.

    • SortExpression - the sort expression associated with the column or columns being sorted.

    • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

  • MailingLists - a list of email lists in your account containing the following information for each email list:

    • ID -the ID of the email list.

    • Name - the name of the email list.

    • ActiveMemberCount - the number of active members in the email list.

    • BouncedMemberCount - the number of bounced emails in the email list.

    • RemovedMemberCount - the number of emails removed from the email list.

    • UnsubscribedMemberCount - the number of emails unsubscribed from the email list.

    • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

    • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list. The parameters are:

      • ID - the ID of the custom field.

      • Name - the name of the custom field

      • Context - the context of the custom field. This is null if the field type is not SingleSelectDropDown.

      • IsRequired - this is true if the custom field is required and false if it is not.

      • Type - the data type of the custom field. Possible values: 0 for text, 1 for number, 2 for dateTime, 3 for SingleSelectDropDown, and 5 for checkbox.

  • CreatedBy - the IP address used to create the requested email list.

  • CreatedOn - the date-time the requested email list was created.

  • UpdatedBy - the IP address used to update the requested email list.

  • UpdatedOn - the date-time the requested email list was updated.

  • ImportOperation - an object that contains the details of the latest import operation performed in the requested email list. This is blank if there was no import done.

    • ID - the ID of the import operation.

    • DataHash - a globally unique identifier (GUID) for the import operation

    • Mappings - the data mappings used for the specific import operation.

    • EmailNotify - this is null if the import operation notification email was not selected to be sent

    • CreatedOn - the date-time when the import operation was created.

    • StartedOn - the date-time when the import operation was stated.

    • CompletedOn - the date-time when the import operation was completed.

    • TotalInserted - the total number of inserted emails.

    • TotalUpdated - the total number of updated emails.

    • TotalUnsubscribed - the total number of unsubscribed emails.

    • TotalInvalid - the total number of invalid emails.

    • TotalIgnored - the total number of ignored emails.

    • TotalDuplicate - the total number of duplicate emails.

    • TotalMembers - the total number of members that were selected to be imported.

    • Message - the message of the import operation. This is null if successful.

    • Success - this is true if successful.

    • SkipNewMembers - this is false if the skip new members option was not selected before the import operation began.

Request
GET https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=
Request
curl --include \
'https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("lists.{Format}{?apikey}{?WithStatistics}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/lists.{Format}{?apikey}{?WithStatistics}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 0,
      "CurrentPage": 1,
      "TotalResults": 90,
      "TotalPageCount": 9,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "MailingLists": [
      {
        "ID": "04fad8e2-2b35-4302-a887-58f14a1152ab",
        "Name": "Your List Name",
        "ActiveMemberCount": 1024,
        "BouncedMemberCount": 16,
        "RemovedMemberCount": 32,
        "UnsubscribedMemberCount": 24,
        "Status": 0,
        "CustomFieldsDefinition": [
          {
            "ID": "dd4fb545-ba00-4afe-bc39-5ed2462fd1d3",
            "Name": "City",
            "Context": null,
            "IsRequired": false,
            "Type": 0
          },
          {
            "ID": "ae8500d7-d1df-4118-9a2c-6654a7d6a6db",
            "Name": "Age",
            "Context": null,
            "IsRequired": true,
            "Type": 1
          }
        ],
        "CreatedBy": "127.0.0.1",
        "CreatedOn": "/Date(1368710504000+0300)/",
        "UpdatedBy": "127.0.0.1",
        "UpdatedOn": "/Date(1368710923000+0300)/",
        "ImportOperation": {
          "ID": 0,
          "DataHash": "97de8bcb-ca1c-4a4b-bf02-3f639952e093",
          "Mappings": "Some Mappings",
          "EmailNotify": "Some EmailNotify",
          "CreatedOn": "/Date(1400765707431)/",
          "StartedOn": "/Date(1400765707431)/",
          "CompletedOn": "/Date(1400765707432)/",
          "TotalInserted": 0,
          "TotalUpdated": 0,
          "TotalUnsubscribed": 0,
          "TotalInvalid": 0,
          "TotalDuplicate": 0,
          "TotalMembers": 0,
          "Message": "Some Message",
          "Success": false
        }
      },
      {
        "ID": "4d90a60c-fad2-4f29-b541-318f0ea82be6",
        "Name": "Some Name",
        "ActiveMemberCount": 0,
        "BouncedMemberCount": 0,
        "RemovedMemberCount": 0,
        "UnsubscribedMemberCount": 0,
        "Status": 0,
        "CustomFieldsDefinition": [
          {
            "ID": "c0adddda-12c1-4109-b7db-9a997f70c81f",
            "Name": "Some Name",
            "Context": "Some Context",
            "IsRequired": false,
            "Type": 0
          },
          {
            "ID": "da5bdc1c-08b2-4b3e-b44b-d56ede6d1a31",
            "Name": "Some Name",
            "Context": "Some Context",
            "IsRequired": false,
            "Type": 0
          }
        ],
        "CreatedBy": "Some CreatedBy",
        "CreatedOn": "/Date(1400765707432)/",
        "UpdatedBy": "Some UpdatedBy",
        "UpdatedOn": "/Date(1400765707432)/",
        "ImportOperation": {
          "ID": 0,
          "DataHash": "7ec702c2-0481-45cc-bf92-72bb4912c60d",
          "Mappings": "Some Mappings",
          "EmailNotify": "Some EmailNotify",
          "CreatedOn": "/Date(1400765707432)/",
          "StartedOn": "/Date(1400765707432)/",
          "CompletedOn": "/Date(1400765707432)/",
          "TotalInserted": 0,
          "TotalUpdated": 0,
          "TotalUnsubscribed": 0,
          "TotalInvalid": 0,
          "TotalDuplicate": 0,
          "TotalMembers": 0,
          "Message": "Some Message",
          "Success": false
        }
      }
    ]
  }
}

Get mailing list details

Abstract

Describes the request and response details of this Moosend API endpoint to get your email list details.

Request

Parameter

In

Type

Required

Description

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

MailingListID

path

string

true

The ID of the email list that contains the details you are requesting.

apikey

query

string

true

The API key of your account.

WithStatistics

query

string

false

Specifies whether to fetch statistics for the subscribers.

Possible values: true (Default) and false.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested email list:

  • ID - the ID of the email list.

  • Name - the name of the email list.

  • ActiveMemberCount - the number of active members in the email list.

  • BouncedMemberCount - the number of bounced emails in the email list.

  • RemovedMemberCount - the number of emails removed from the email list.

  • UnsubscribedMemberCount - the number of emails unsubscribed from the email list.

  • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

  • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list. The parameters are:

    • ID - the ID of the custom field.

    • Name - the name of the custom field

    • Context - the context of the custom field. This is null if the field type is not SingleSelectDropDown.

    • IsRequired - this is true if the custom field is required and false if it is not.

    • Type - the data type of the custom field. Possible values: 0 for text, 1 for number, 2 for dateTime, 3 for SingleSelectDropDown, and 5 for checkbox.

  • CreatedBy - the IP address used to create the requested email list.

  • CreatedOn - the date-time the requested email list was created.

  • UpdatedBy - the IP address used to update the requested email list.

  • UpdatedOn - the date-time the requested email list was updated.

  • ImportOperation - an object that contains the details of the latest import operation performed in the requested email list. This is blank if there was no import done.

    • ID - the ID of the import operation.

    • DataHash - a globally unique identifier (GUID) for the import operation

    • Mappings - the data mappings used for the specific import operation.

    • EmailNotify - this is null if the import operation notification email was not selected to be sent

    • CreatedOn - the date-time when the import operation was created.

    • StartedOn - the date-time when the import operation was stated.

    • CompletedOn - the date-time when the import operation was completed.

    • TotalInserted - the total number of inserted emails.

    • TotalUpdated - the total number of updated emails.

    • TotalUnsubscribed - the total number of unsubscribed emails.

    • TotalInvalid - the total number of invalid emails.

    • TotalIgnored - the total number of ignored emails.

    • TotalDuplicate - the total number of duplicate emails.

    • TotalMembers - the total number of members that were selected to be imported.

    • Message - the message of the import operation. This is null if successful.

    • Success - this is true if successful.

    • SkipNewMembers - this is false if the skip new members option was not selected before the import operation began.

Request
GET https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=
Request
curl --include \
'https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}v/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("lists.{Format}{?apikey}{?WithStatistics}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/lists.{Format}{?apikey}{?WithStatistics}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "28132257-f655-49a4-8af7-6fbf31645641",
    "Name": "test auto",
    "ActiveMemberCount": 19999,
    "BouncedMemberCount": 0,
    "RemovedMemberCount": 0,
    "UnsubscribedMemberCount": 0,
    "Status": 1,
    "CustomFieldsDefinition": [
      {
        "ID": "c3226cc-8a18-4f22-907b-8422d61a53a1",
        "Name": "Gender",
        "Context": "<items><item><name>Male</name><value>Male</value></item><item><name>Female</name><value>Female</value></item></items>",
        "IsRequired": true,
        "Type": 3
      },
      {
        "ID": "bf14b37c-3c47-412d-baf1-c6850b8cf2af",
        "Name": "Town",
        "Context": null,
        "IsRequired": false,
        "Type": 0
      }
    ],
    "CreatedBy": "223.16.165.23",
    "CreatedOn": "/Date(1443174387327+0100)/",
    "UpdatedBy": "223.16.165.23",
    "UpdatedOn": "/Date(1443174387327+0100)/",
    "ImportOperation": {
      "ID": 3706,
      "DataHash": "2490c26c-79f6-a52c-4afb-852f624a91b0",
      "Mappings": "Email",
      "EmailNotify": null,
      "CreatedOn": "/Date(1443181931130+0100)/",
      "StartedOn": "/Date(1443181958330+0100)/",
      "CompletedOn": "/Date(1443182730673+0100)/",
      "TotalInserted": 19999,
      "TotalUpdated": 0,
      "TotalUnsubscribed": 1,
      "TotalInvalid": 0,
      "TotalIgnored": 0,
      "TotalDuplicate": 0,
      "TotalMembers": 20000,
      "Message": null,
      "Success": true,
      "SkipNewMembers": false
    }
  }
}

Get all active mailing lists with paging

Abstract

Describes the request and response details of this Moosend API endpoint to get your active email lists with paging information included.

Request

Parameter

In

Type

Required

Description

Page

path

number

false

The page that you want to get.

PageSize

path

number

false

The number of email lists per page.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

ShortBy

query

string

false

The name of the email list property to sort results by.

Possible values: Name, Subject, Status, DeliveredOn, and CreatedOn (Default).

SortMethod

query

string

false

Specifies the method to sort results.

Possible values: DESC for descending and ASC (Default) for ascending.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and MailingLists information for the requested email list:

  • Paging - an object that contains the following information:

    • PageSize - the page size of the results. This is 0 if not defined.

    • CurrentPage - the number of the result page. This is 1 if not defined.

    • Totalresults - the number of email lists that are included in the response.

    • TotalPageCount - the total number of available email list pages in your account.

    • SortExpression - the sort expression associated with the column or columns being sorted.

    • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

  • MailingLists - a list of email lists in your account containing the following information for each email list:

    • ID -the ID of the email list.

    • Name - the name of the email list.

    • ActiveMemberCount - the number of active members in the email list.

    • BouncedMemberCount - the number of bounced emails in the email list.

    • RemovedMemberCount - the number of emails removed from the email list.

    • UnsubscribedMemberCount - the number of emails unsubscribed from the email list.

    • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

    • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list. The parameters are:

      • ID - the ID of the custom field.

      • Name - the name of the custom field

      • Context - the context of the custom field. This is null if the field type is not SingleSelectDropDown.

      • IsRequired - this is true if the custom field is required and false if it is not.

      • Type - the data type of the custom field. Possible values: 0 for text, 1 for number, 2 for dateTime, 3 for SingleSelectDropDown, and 5 for checkbox.

  • CreatedBy - the IP address used to create the requested email list.

  • CreatedOn - the date-time the requested email list was created.

  • UpdatedBy - the IP address used to update the requested email list.

  • UpdatedOn - the date-time the requested email list was updated.

  • ImportOperation - an object that contains the details of the latest import operation performed in the requested email list. This is blank if there was no import done.

    • ID - the ID of the import operation.

    • DataHash - a globally unique identifier (GUID) for the import operation

    • Mappings - the data mappings used for the specific import operation.

    • EmailNotify - this is null if the import operation notification email was not selected to be sent

    • CreatedOn - the date-time when the import operation was created.

    • StartedOn - the date-time when the import operation was stated.

    • CompletedOn - the date-time when the import operation was completed.

    • TotalInserted - the total number of inserted emails.

    • TotalUpdated - the total number of updated emails.

    • TotalUnsubscribed - the total number of unsubscribed emails.

    • TotalInvalid - the total number of invalid emails.

    • TotalIgnored - the total number of ignored emails.

    • TotalDuplicate - the total number of duplicate emails.

    • TotalMembers - the total number of members that were selected to be imported.

    • Message - the message of the import operation. This is null if successful.

    • Success - this is true if successful.

    • SkipNewMembers - this is false if the skip new members option was not selected before the import operation began.

Request
GET https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=
Request
curl --include \
'https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("lists.{Format}{?apikey}{?WithStatistics}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/lists.{Format}{?apikey}{?WithStatistics}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 20,
      "CurrentPage": 1,
      "TotalResults": 92,
      "TotalPageCount": 5,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "MailingLists": [
      {
        "ID": "04fad8e2-2b35-4302-a887-58f14a1152ab",
        "Name": "Your List Name",
        "ActiveMemberCount": 1024,
        "BouncedMemberCount": 16,
        "RemovedMemberCount": 32,
        "UnsubscribedMemberCount": 24,
        "Status": 0,
        "CustomFieldsDefinition": [
          {
            "ID": "dd4fb545-ba00-4afe-bc39-5ed2462fd1d3",
            "Name": "City",
            "Context": null,
            "IsRequired": false,
            "Type": 0
          },
          {
            "ID": "ae8500d7-d1df-4118-9a2c-6654a7d6a6db",
            "Name": "Age",
            "Context": null,
            "IsRequired": true,
            "Type": 1
          }
        ],
        "CreatedBy": "127.0.0.1",
        "CreatedOn": "/Date(1368710504000+0300)/",
        "UpdatedBy": "127.0.0.1",
        "UpdatedOn": "/Date(1368710923000+0300)/",
        "ImportOperation": {
          "ID": 0,
          "DataHash": "97de8bcb-ca1c-4a4b-bf02-3f639952e093",
          "Mappings": "Some Mappings",
          "EmailNotify": "Some EmailNotify",
          "CreatedOn": "/Date(1400765707431)/",
          "StartedOn": "/Date(1400765707431)/",
          "CompletedOn": "/Date(1400765707432)/",
          "TotalInserted": 0,
          "TotalUpdated": 0,
          "TotalUnsubscribed": 0,
          "TotalInvalid": 0,
          "TotalDuplicate": 0,
          "TotalMembers": 0,
          "Message": "Some Message",
          "Success": false
        }
      },
      {
        "ID": "4d90a60c-fad2-4f29-b541-318f0ea82be6",
        "Name": "Some Name",
        "ActiveMemberCount": 0,
        "BouncedMemberCount": 0,
        "RemovedMemberCount": 0,
        "UnsubscribedMemberCount": 0,
        "Status": 0,
        "CustomFieldsDefinition": [],
        "CreatedBy": "192.168.1.1",
        "CreatedOn": "/Date(1400765707432)/",
        "UpdatedBy": "192.168.1.1",
        "UpdatedOn": "/Date(1400765707432)/",
        "ImportOperation": {
          "ID": 0,
          "DataHash": "7ec702c2-0481-45cc-bf92-72bb4912c60d",
          "Mappings": "Some Mappings",
          "EmailNotify": "Some EmailNotify",
          "CreatedOn": "/Date(1400765707432)/",
          "StartedOn": "/Date(1400765707432)/",
          "CompletedOn": "/Date(1400765707432)/",
          "TotalInserted": 0,
          "TotalUpdated": 0,
          "TotalUnsubscribed": 0,
          "TotalInvalid": 0,
          "TotalDuplicate": 0,
          "TotalMembers": 0,
          "Message": "Some Message",
          "Success": false
        }
      }
    ]
  }
}

Create a mailing list

Abstract

Describes the request and response details of this Moosend API endpoint to create an email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the email list.

ConfirmationPage

body

string

false

The URL of the page displayed at the end of the subscription process.

RedirectAfterUnsubscribePage

body

string

false

The URL of the redirect page when users unsubscribe from your email list.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the email list created.

Request
POST https://{hostname}/v3/lists/create.{Format}?apikey=

Request body:
{
  "Name": "New List",
  "ConfirmationPage": "www.someUrl.com",
  "RedirectAfterUnsubscribePage": "www.someUrl.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"New List\",
    \"ConfirmationPage\":\"www.someUrl.com\",
    \"RedirectAfterUnsubscribePage\":\"www.someUrl.com\"
}" \
'https://{hostname}/v3/lists/create.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"New List\",  \"ConfirmationPage\": \"www.someUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"}");
Response response = client.target("https://{hostname}/v3/lists/create.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/create.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'New List',
  'ConfirmationPage': 'www.someUrl.com',
  'RedirectAfterUnsubscribePage': 'www.someUrl.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/create.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"New List\",  \"ConfirmationPage\": \"www.someUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "New List",  "ConfirmationPage": "www.someUrl.com",  "RedirectAfterUnsubscribePage": "www.someUrl.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/create.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "New List",
    "ConfirmationPage": "www.someUrl.com",
    "RedirectAfterUnsubscribePage": "www.someUrl.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/create.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/create.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"New List\",
  \"ConfirmationPage\": \"www.someUrl.com\",
  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "New List",
  "ConfirmationPage": "www.someUrl.com",
  "RedirectAfterUnsubscribePage": "www.someUrl.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/create.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"New List\",\n  \"ConfirmationPage\": \"www.someUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/create.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"New List\",  \"ConfirmationPage\": \"www.someUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/create.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""New List\"",
  \""ConfirmationPage\"": \""www.someUrl.com\"",
  \""RedirectAfterUnsubscribePage\"": \""www.someUrl.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "New List",
  "ConfirmationPage": "www.someUrl.com",
  "RedirectAfterUnsubscribePage": "www.someUrl.com"
}')
response = client.post( path : "/Mailing Lists/lists/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/create.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"New List\",\n  \"ConfirmationPage\": \"www.someUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/create.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"New List\",\n  \"ConfirmationPage\": \"www.someUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "6ca52d31-765c-4760-a78e-91e511e49d76"
}

Update a mailing list

Abstract

Describes the request and response details of this Moosend API endpoint to update an email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list to be updated.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the email list.

ConfirmationPage

body

string

false

The URL of the page displayed at the end of the subscription process.

RedirectAfterUnsubscribePage

body

string

false

The URL of the redirect page when users unsubscribe from your email list.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the updated email list.

Request
POST https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=

Request body:
{
  "Name": "New List Name",
  "ConfirmationPage": "www.someotherUrl.com",
  "RedirectAfterUnsubscribePage": "www.someotherUrl.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"New List Name\",
    \"ConfirmationPage\":\"www.someotherUrl.com\",
    \"RedirectAfterUnsubscribePage\":\"www.someotherUrl.com\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"New List Name\",  \"ConfirmationPage\": \"www.someotherUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'New List Name',
  'ConfirmationPage': 'www.someotherUrl.com',
  'RedirectAfterUnsubscribePage': 'www.someotherUrl.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"New List Name\",  \"ConfirmationPage\": \"www.someotherUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "New List Name",  "ConfirmationPage": "www.someotherUrl.com",  "RedirectAfterUnsubscribePage": "www.someotherUrl.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "New List Name",
    "ConfirmationPage": "www.someotherUrl.com",
    "RedirectAfterUnsubscribePage": "www.someotherUrl.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"New List Name\",
  \"ConfirmationPage\": \"www.someotherUrl.com\",
  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "New List Name",
  "ConfirmationPage": "www.someotherUrl.com",
  "RedirectAfterUnsubscribePage": "www.someotherUrl.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"New List Name\",\n  \"ConfirmationPage\": \"www.someotherUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"New List Name\",  \"ConfirmationPage\": \"www.someotherUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""New List Name\"",
  \""ConfirmationPage\"": \""www.someotherUrl.com\"",
  \""RedirectAfterUnsubscribePage\"": \""www.someotherUrl.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "New List Name",
  "ConfirmationPage": "www.someotherUrl.com",
  "RedirectAfterUnsubscribePage": "www.someotherUrl.com"
}')
response = client.post( path : "/Mailing Lists/lists/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"New List Name\",\n  \"ConfirmationPage\": \"www.someotherUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"New List Name\",\n  \"ConfirmationPage\": \"www.someotherUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "e5f6c0a3-1fe6-4d89-951e-eafae0b01368"
}

Delete a mailing list

Abstract

Describes the request and response details of this Moosend API endpoint to delete an email list.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list to be deleted.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response error message. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
DELETE https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=
Request
curl --include \
     --request DELETE \
'https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .delete();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('DELETE', 'https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'DELETE',
  url: 'https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->delete("https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=')
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.delete 'https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("DELETE", "https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.DeleteAsync("Mailing Lists/lists/create.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "DELETE"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.delete( path : "/Mailing Lists/lists/create.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"DELETE"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "DELETE"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Create a custom field

Abstract

Describes the request and response details of this Moosend API endpoint to create a custom field.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list where the custom field is created.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the custom field.

CustomFieldType

body

string

false

Specifies the data type of the custom field. This must be one of the following values.

  • Text (Default) - accepts any text value as input.

  • Number - accepts only numeric values as input.

  • DateTime - accepts only date values as input, with or without time.

  • SingleSelectDropdown - accepts only values explicitly defined in a list.

  • CheckBox - accepts only values of true or false.

Options

body

string

false

If you want to create a SingleSelectDropdown custom field, you must set this parameter to specify the available options for the user to choose from. Use a comma (,) to separate different options.

IsRequired

body

Boolean

false

Specifies whether the custom field is mandatory or not when adding a subscriber to your list. You must specify a value of true or false (Default).

IsHidden

body

Boolean

false

Specifies whether the custom field is visible to your subscribers in the Update Profile page. You must specify a value of true or false (Default).

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the custom field created.

Request
POST https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=

Request body:
{
  "Name": "Town",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Athens,London,New York"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\": \"Town\",
    \"CustomFieldType\":\"SingleSelectDropdown\",
    \"Options\":\"Athens,London,New York\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Town\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Athens,London,New York\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Town',
  'CustomFieldType': 'SingleSelectDropdown',
  'Options': 'Athens,London,New York'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Town\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Athens,London,New York\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Town",  "CustomFieldType": "SingleSelectDropdown",  "Options": "Athens,London,New York"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Town",
    "CustomFieldType": "SingleSelectDropdown",
    "Options": "Athens,London,New York"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Town\",
  \"CustomFieldType\": \"SingleSelectDropdown\",
  \"Options\": \"Athens,London,New York\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Town",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Athens,London,New York"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Town\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Athens,London,New York\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Town\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Athens,London,New York\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Town\"",
  \""CustomFieldType\"": \""SingleSelectDropdown\"",
  \""Options\"": \""Athens,London,New York\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Town",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Athens,London,New York"
}')
response = client.post( path : "/Mailing Lists/lists/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Town\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Athens,London,New York\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Town\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Athens,London,New York\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "b42b4e0f-ca2f-403d-8231-32a2405651af"
}

Update a custom field

Abstract

Describes the request and response details of this Moosend API endpoint to update a custom field.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list containing the custom field.

CustomFieldID

path

string

true

The ID of the custom field to be updated.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the custom field.

CustomFieldType

body

string

false

Specifies the data type of the custom field. This must be one of the following values.

  • Text (Default) - accepts any text value as input.

  • Number - accepts only numeric values as input.

  • DateTime - accepts only date values as input, with or without time.

  • SingleSelectDropdown - accepts only values explicitly defined in a list.

  • CheckBox - accepts only values of true or false.

Options

body

string

false

If you want to update a SingleSelectDropdown custom field, you must set this parameter to specify the available options for the user to choose from. Use a comma (,) to separate different options.

IsRequired

body

Boolean

false

Specifies whether the custom field is mandatory or not when adding a subscriber to your list. You must specify a value of true or false (Default).

IsHidden

body

Boolean

false

Specifies whether the custom field is visible to your subscribers in the Update Profile page. You must specify a value of true or false (Default).

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=

Request body:
{
  "Name": "City",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Frankfurt,London,Paris,Rome"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\": \"City\",
    \"CustomFieldType\":\"SingleSelectDropdown\",
    \"Options\":\"Frankfurt,London,Paris,Rome\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"City\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Frankfurt,London,Paris,Rome\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'City',
  'CustomFieldType': 'SingleSelectDropdown',
  'Options': 'Frankfurt,London,Paris,Rome'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"City\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Frankfurt,London,Paris,Rome\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "City",  "CustomFieldType": "SingleSelectDropdown",  "Options": "Frankfurt,London,Paris,Rome"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "City",
    "CustomFieldType": "SingleSelectDropdown",
    "Options": "Frankfurt,London,Paris,Rome"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"City\",
  \"CustomFieldType\": \"SingleSelectDropdown\",
  \"Options\": \"Frankfurt,London,Paris,Rome\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "City",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Frankfurt,London,Paris,Rome"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"City\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Frankfurt,London,Paris,Rome\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"City\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Frankfurt,London,Paris,Rome\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""City\"",
  \""CustomFieldType\"": \""SingleSelectDropdown\"",
  \""Options\"": \""Frankfurt,London,Paris,Rome\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "City",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Frankfurt,London,Paris,Rome"
}')
response = client.post( path : "/Mailing Lists/lists/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"City\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Frankfurt,London,Paris,Rome\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"City\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Frankfurt,London,Paris,Rome\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "null"
}

Remove a custom field

Abstract

Describes the request and response details of this Moosend API endpoint to remove a custom field.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list containing the custom field.

CustomFieldID

path

string

true

The ID of the custom field to be deleted.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
DELETE https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=
Request
curl --include \
     --request DELETE \
'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .delete();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('DELETE', 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'DELETE',
  url: 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->delete("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=')
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.delete 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("DELETE", "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.DeleteAsync("Mailing Lists/lists/create.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https:/{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "DELETE"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.delete( path : "/Mailing Lists/lists/create.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"DELETE"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "DELETE"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Subscribers

Abstract

Describes how to use the Moosend API to get, add, update, unsubscribe, and remove subscribers from email lists in your account.

Use the Moosend API to fetch your subscribers, get details about your subscribers, add, update, remove subscribers, and unsubscribe subscribers from email lists or campaigns.

Get all subscribers

Abstract

Describes the request and response details of this Moosend API endpoint to get all your subscribers.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list containing the subscribers.

Status

path

string

true

Specifies the type of subscriber statistics results to return.

Possible values: Subscribed , Unsubscribed BouncedRemoved.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Page

path

number

false

The page of subscriber statistics results to return.

PageSize

path

number

false

The page size of subscriber statistics results to return.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and Subscribers information in the specific email list:

  • Paging - an object that contains the following information:

    • PageSize - the page size of the results. This is 0 if not defined.

    • CurrentPage - the number of the result page. This is 1 if not defined.

    • Totalresults - the number of all the subscribers that are included in the response.

    • TotalPageCount - the total number of available subscriber pages in your account.

    • SortExpression - the sort expression associated with the column or columns being sorted.

    • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

  • Subscribers - a list of subscribers in the email list containing the following information for each subscriber:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
GET https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=
Request
curl --include \
'https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=')

response_body = urlopen(r
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("Mailing Lists/subscribers/{Status}.{Format}{?apikey}{?Page}{?PageSize}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/Mailing Lists/subscribers/{Status}.{Format}{?apikey}{?Page}{?PageSize}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 500,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": "CreatedOn",
      "SortIsAscending": false
    },
    "Subscribers": [
      {
        "ID": "4d03536e-7263-4a45-add0-8fe9568d7481",
        "Name": "Maria",
        "Email": "maria@email.com",
        "CreatedOn": "/Date(1456236266953+0000)/",
        "UpdatedOn": "/Date(1465286948363+0100)/",
        "UnsubscribedOn": null,
        "UnsubscribedFromID": null,
        "SubscribeType": 1,
        "SubscribeMethod": 2,
        "CustomFields": [
          {
            "CustomFieldID": "dbc599a6-3ac0-4843-830c-31fa78699fcc",
            "Name": "ID",
            "Value": "1233"
          },
          {
            "CustomFieldID": "bfe484f1-030f-4f8d-bdfa-93abc3b227c0",
            "Name": "City",
            "Value": "Athens"
          }
        ],
        "RemovedOn": null,
        "Tags": [
            "potential",
            "repeater"
        ]
      },
      {
        "ID": "83485f6c-569c-4012-ab2e-f91d3f888995",
        "Name": "Andreas",
        "Email": "andreas@email.com",
        "CreatedOn": "/Date(1454421397847+0000)/",
        "UpdatedOn": "/Date(1465286972657+0100)/",
        "UnsubscribedOn": null,
        "UnsubscribedFromID": null,
        "SubscribeType": 1,
        "SubscribeMethod": 2,
        "CustomFields": [
          {
            "CustomFieldID": "dbc599a6-3ac0-4843-830c-31fa78699fcc",
            "Name": "ID",
            "Value": "1333"
          },
          {
            "CustomFieldID": "bfe484f1-030f-4f8d-bdfa-93abc3b227c0",
            "Name": "City",
            "Value": "Liverpool"
          }
        ],
        "RemovedOn": null,
        "Tags": [
            "potential",
            "repeater"
        ]
      }
    ]
  }
}

Get subscriber by email address

Abstract

Describes the request and response details of this Moosend API endpoint to get a specific subscriber by email address.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list that contains the subscriber.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

query

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested subscriber:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
GET https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=
Request
curl --include \
'https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("subscribers/{MailingListID}/view.{Format}{?apikey}{?Email}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/subscribers/{MailingListID}/view.{Format}{?apikey}{?Email}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "9bef1735-f04d-4472-b029-68eb7fa2cfe7",
    "Name": "Andreas",
    "Email": "andreas@email.com",
    "CreatedOn": "/Date(1461777152597+0100)/",
    "UpdatedOn": "/Date(1461777152597+0100)/",
    "UnsubscribedOn": null,
    "UnsubscribedFromID": null,
    "SubscribeType": 1,
    "SubscribeMethod": 2,
    "CustomFields": [
      {
        "CustomFieldID": "b7e68e81-b6ab-4caa-8d13-e65871b32386",
        "Name": "Registered",
        "Value": "4/21/2016 12:00:00 AM"
      },
      {
        "CustomFieldID": "9df6dcc4-bef2-47e7-93af-86889b6b6d6a",
        "Name": "Age",
        "Value": "24"
      },
      {
        "CustomFieldID": "0d2199aa-65fc-448c-b9fe-199e3b72ebc5",
        "Name": "Some custom field",
        "Value": "Something"
      },
      {
        "CustomFieldID": "46721a6b-09aa-46ff-bab1-a0b75dea24cf",
        "Name": "Some custom field",
        "Value": "Text1"
      }
    ],
    "RemovedOn": null,
    "Tags": [
            "potential",
            "repeater"
        ]
  }
}

Get subscriber by ID

Abstract

Describes the request and response details of this Moosend API endpoint to get a specific subscriber by ID.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list that contains the subscriber.

SubscriberID

path

string

true

The ID of the subscriber.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the subscriber:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
GET https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("subscribers/{MailingListID}/view.{Format}{?apikey}{?Email}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/subscribers/{MailingListID}/view.{Format}{?apikey}{?Email}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "118e41dc-bb9e-435d-a86a-e5bd374668a8",
    "Name": "Some name",
    "Email": "getmoocampaigns+1@gmail.com",
    "CreatedOn": "/Date(1464952683773+0100)/",
    "UpdatedOn": "/Date(1465380328390+0100)/",
    "UnsubscribedOn": null,
    "UnsubscribedFromID": null,
    "SubscribeType": 4,
    "SubscribeMethod": 2,
    "CustomFields": [],
    "RemovedOn": "/Date(1465381597743+0100)/",
    "Tags": []
  }
}

Add a new subscriber

Abstract

Describes the request and response details of this Moosend API endpoint to add a new subscriber to an email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list where you want to add a new subscriber.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

false

The name of the new subscriber.

Email

body

string

true

The email address of the new subscriber.

HasExternalDoubleOptIn

body

Boolean

false

When true, it flags the added subscriber as having given subscription consent by other means.

CustomFields

body

array

false

A list of name-value pairs that match the subscriber’s custom fields defined in the email list.

For example, if you have two custom fields for Age and Country, you must specify the values for these two fields.

Tags

body

object

false

The member tag you can use to filter members by when working with an email list.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the new subscriber added to the email list:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
POST /v3/subscribers/{MailingListID}/subscribe.{Format}?apikey= HTTP/1.1
Host: {hostname}

{
    "Name" : "Paul",
    "Email" : "someEmail@email.com",
    "HasExternalDoubleOptIn": false,
    "CustomFields": [
        "Age=25",
        "Country=USA"
    ],
    "Tags": [
        "repeater"
    ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\" : \"Paul\",
    \"Email\" : \"someEmail@email.com\",
    \"HasExternalDoubleOptIn\": false,
    \"CustomFields\": [
        \"Age=25\",
        \"Country=USA\"
    ],
    \"Tags\": [
        \"repeater\"
    ]
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey='
Request

Request
$.ajax({
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=',
  crossDomain: true,
  method: 'post',
  headers: {
    'Accept': 'application/json'
  },
  contentType: 'application/json',
  // data: '{\n    "Name" : "Paul",\n    "Email" : "someEmail@email.com",\n    "HasExternalDoubleOptIn": false,\n    "CustomFields": [\n        "Age=25",\n        "Country=USA"\n    ],\n    "Tags": [\n        "repeater"\n    ]\n}',
  data: JSON.stringify({
    'Name': 'Paul',
    'Email': 'someEmail@email.com',
    'HasExternalDoubleOptIn': false,
    'CustomFields': [
      'Age=25',
      'Country=USA'
    ],
    'Tags': [
      'repeater'
    ]
  })
}).done(function(response) {
  console.log(response);
});
Request
var request = require('request');

var headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
};

var dataString = '{\n    "Name" : "Paul",\n    "Email" : "someEmail@email.com",\n    "HasExternalDoubleOptIn": false,\n    "CustomFields": [\n        "Age=25",\n        "Country=USA"\n    ],\n    "Tags": [\n        "repeater"\n    ]\n}';

var options = {
    url: 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=',
    method: 'POST',
    headers: headers,
    body: dataString
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

request(options, callback);
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Paul",  "Email": "someEmail@email.com",  "HasExternalDoubleOptIn": false,  "CustomFields": [    "Age=25",    "Country=USA"  ],
            "Tags": [
                "repeater"
            ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
import requests

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}

params = {
    'apikey': '',
}

json_data = {
    'Name': 'Paul',
    'Email': 'someEmail@email.com',
    'HasExternalDoubleOptIn': False,
    'CustomFields': [
        'Age=25',
        'Country=USA',
    ],
    'Tags': [
        'repeater',
    ],
}

response = requests.post(
    'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}',
    params=params,
    headers=headers,
    json=json_data,
)

# Note: json_data will not be serialized by requests
# exactly as it was in the original request.
#data = '{\n    "Name" : "Paul",\n    "Email" : "someEmail@email.com",\n    "HasExternalDoubleOptIn": false,\n    "CustomFields": [\n        "Age=25",\n        "Country=USA"\n    ],\n    "Tags": [\n        "repeater"\n    ]\n}'
#response = requests.post(
#    'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}',
#    params=params,
#    headers=headers,
#    data=data,
#)
Request
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Accept: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}");

$response = curl_exec($ch);

curl_close($ch);
Request
require 'net/http'
require 'json'

uri = URI('https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}')
params = {
  :apikey => '',
}
uri.query = URI.encode_www_form(params)

req = Net::HTTP::Post.new(uri)
req.content_type = 'application/json'
req['Accept'] = 'application/json'

# The object won't be serialized exactly like this
# req.body = "{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}"
req.body = {
  'Name' => 'Paul',
  'Email' => 'someEmail@email.com',
  'HasExternalDoubleOptIn' => false,
  'CustomFields' => [
    'Age=25',
    'Country=USA'
  ],
  'Tags' => [
    'repeater'
  ]
}.to_json

req_options = {
  use_ssl: uri.scheme == 'https'
}
res = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(req)
end
Request
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
)

func main() {
	client := &http.Client{}
	var data = strings.NewReader(`{
    "Name" : "Paul",
    "Email" : "someEmail@email.com",
    "HasExternalDoubleOptIn": false,
    "CustomFields": [
        "Age=25",
        "Country=USA"
    ],
    "Tags": [
        "repeater"
    ]
}`)
	req, err := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=", data)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", bodyText)
}
Request
using System.Net.Http;
using System.Net.Http.Headers;

HttpClient client = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=");

request.Headers.Add("Accept", "application/json");

request.Content = new StringContent("{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Paul\"",
  \""Email\"": \""someEmail@email.com\"",
  \""HasExternalDoubleOptIn\"": false,
  \""CustomFields\"": [
    \""Age=25\"",
    \""Country=USA\""
  ],
            "Tags": [
                "repeater"
            ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Paul",
  "Email": "someEmail@email.com",
  "HasExternalDoubleOptIn": false,
  "CustomFields": [
    "Age=25",
    "Country=USA"
  ],
            "Tags": [
                "repeater"
            ]
}')
response = client.post( path : "/subscribers/{MailingListID}/subscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
#import <Foundation/Foundation.h>

NSURL *url = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey="];
NSDictionary *headers = @{
    @"Content-Type": @"application/json",
    @"Accept": @"application/json"
};

NSMutableData *data = [[NSMutableData alloc] initWithData:[@"{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:data];

NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"%@", error);
    } else {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSLog(@"%@", httpResponse);
    }
}];
[dataTask resume];
Request
import Foundation

let jsonData = [
    "Name": "Paul",
    "Email": "someEmail@email.com",
    "HasExternalDoubleOptIn": false,
    "CustomFields": [
        "Age=25",
        "Country=USA"
    ],
    "Tags": [
        "repeater"
    ]
] as [String : Any]
let data = try! JSONSerialization.data(withJSONObject: jsonData, options: [])
// let data = "{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}".data(using: .utf8)

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=")!
let headers = [
    "Content-Type": "application/json",
    "Accept": "application/json"
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = data as Data

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print(error)
    } else if let data = data {
        let str = String(data: data, encoding: .utf8)
        print(str ?? "")
    }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "f582c388-7916-4890-a9ab-b592615ef095",
    "Name": "Paul",
    "Email": "someemail@email.com",
    "CreatedOn": "/Date(1465379934028)/",
    "UpdatedOn": "/Date(1465379934028)/",
    "UnsubscribedOn": null,
    "UnsubscribedFromID": null,
    "SubscribeType": 1,
    "SubscribeMethod": 2,
    "CustomFields": [
      {
        "CustomFieldID": "728f6774-37ea-4d81-8607-ce8308136760",
        "Name": "Age",
        "Value": "25"
      },
      {
        "CustomFieldID": "b6380e04-c3a6-425b-9931-d25897fa4752",
        "Name": "Country",
        "Value": "USA"
      }
    ],
    "RemovedOn": null,
    "Tags": [
       "potential",
       "repeater"
    ]  
    }
}

Add multiple subscribers

Abstract

Describes the request and response details of this Moosend API endpoint to add multiple subscribers to an email list in a single request.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list where you want to add multiple subscribers.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

HasExternalDoubleOptIn

body

Boolean

false

When true, it flags the added subscribers as having given their subscription consent by other means.

Subscribers

body

array

true

A list containing up to 1000 subscribers that you are adding to the email list. You must specify the Name, Email, and CustomFields for each subscriber.

Tags

body

object

false

The member tag you can use to filter members by when working with an email list.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Erros - the response error message that shows how many and which emails are invalid. It is null if all emails are valid.

  • Context - an object that contains all the following information for each new subscriber added to the email list:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
POST /v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey= HTTP/1.1
Host: {hostname}

{  
    "HasExternalDoubleOptIn": false,
    "Subscribers":[  
      {  
         "Name":"test1Email",
         "Email":"test1@test.com",
         "CustomFields":[  
            "Country=UK"
         ]
      },
      {  
         "Name":"test2133Email",
         "Email":"test2133@test.com",
         "CustomFields":[  
            "Age=25",
            "Country=USA"
         ],
         "Tags": [
            "repeater"
         ]
      }
   ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{  
    \"HasExternalDoubleOptIn\": false,
    \"Subscribers\":[  
      {  
         \"Name\":\"test1Email\",
         \"Email\":\"test1@test.com\",
         \"CustomFields\":[  
            \"Country=UK\"
         ]
      },
      {  
         \"Name\":\"test2133Email\",
         \"Email\":\"test2133@test.com\",
         \"CustomFields\":[  
            \"Age=25\",
            \"Country=USA\"
         ],
         \"Tags\": [
            \"repeater\"
         ]
      }
   ]
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey='
Request
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey="))
    .POST(BodyPublishers.ofString("{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}"))
    .setHeader("Content-Type", "application/json")
    .setHeader("Accept", "application/json")
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Request
$.ajax({
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=',
  crossDomain: true,
  method: 'post',
  headers: {
    'Accept': 'application/json'
  },
  contentType: 'application/json',
  // data: '{  \n    "HasExternalDoubleOptIn": false,\n    "Subscribers":[  \n      {  \n         "Name":"test1Email",\n         "Email":"test1@test.com",\n         "CustomFields":[  \n            "Country=UK"\n         ]\n      },\n      {  \n         "Name":"test2133Email",\n         "Email":"test2133@test.com",\n         "CustomFields":[  \n            "Age=25",\n            "Country=USA"\n         ],\n         "Tags": [\n            "repeater"\n         ]\n      }\n   ]\n}',
  data: JSON.stringify({
    'HasExternalDoubleOptIn': false,
    'Subscribers': [
      {
        'Name': 'test1Email',
        'Email': 'test1@test.com',
        'CustomFields': [
          'Country=UK'
        ]
      },
      {
        'Name': 'test2133Email',
        'Email': 'test2133@test.com',
        'CustomFields': [
          'Age=25',
          'Country=USA'
        ],
        'Tags': [
          'repeater'
        ]
      }
    ]
  })
}).done(function(response) {
  console.log(response);
});
Request
var request = require('request');

var headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
};

var dataString = '{  \n    "HasExternalDoubleOptIn": false,\n    "Subscribers":[  \n      {  \n         "Name":"test1Email",\n         "Email":"test1@test.com",\n         "CustomFields":[  \n            "Country=UK"\n         ]\n      },\n      {  \n         "Name":"test2133Email",\n         "Email":"test2133@test.com",\n         "CustomFields":[  \n            "Age=25",\n            "Country=USA"\n         ],\n         "Tags": [\n            "repeater"\n         ]\n      }\n   ]\n}';

var options = {
    url: 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=',
    method: 'POST',
    headers: headers,
    body: dataString
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

request(options, callback);
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "HasExternalDoubleOptIn": false,  "Subscribers": [    {      "Name": "test1Email",      "Email": "test1@test.com",      "CustomFields": [        "Country=UK"      ]    },    {      "Name": "test2133Email",      "Email": "test2133@test.com",      "CustomFields": [        "Age=25",        "Country=USA"      ],
            "Tags": [
                "repeater"
            ]    }  ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
import requests

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}

params = {
    'apikey': '',
}

json_data = {
    'HasExternalDoubleOptIn': False,
    'Subscribers': [
        {
            'Name': 'test1Email',
            'Email': 'test1@test.com',
            'CustomFields': [
                'Country=UK',
            ],
        },
        {
            'Name': 'test2133Email',
            'Email': 'test2133@test.com',
            'CustomFields': [
                'Age=25',
                'Country=USA',
            ],
            'Tags': [
                'repeater',
            ],
        },
    ],
}

response = requests.post(
    'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}',
    params=params,
    headers=headers,
    json=json_data,
)

# Note: json_data will not be serialized by requests
# exactly as it was in the original request.
#data = '{  \n    "HasExternalDoubleOptIn": false,\n    "Subscribers":[  \n      {  \n         "Name":"test1Email",\n         "Email":"test1@test.com",\n         "CustomFields":[  \n            "Country=UK"\n         ]\n      },\n      {  \n         "Name":"test2133Email",\n         "Email":"test2133@test.com",\n         "CustomFields":[  \n            "Age=25",\n            "Country=USA"\n         ],\n         "Tags": [\n            "repeater"\n         ]\n      }\n   ]\n}'
#response = requests.post(
#    'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}',
#    params=params,
#    headers=headers,
#    data=data,
#)
Request
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Accept: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}");

$response = curl_exec($ch);

curl_close($ch);
Request
require 'net/http'
require 'json'

uri = URI('https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}')
params = {
  :apikey => '',
}
uri.query = URI.encode_www_form(params)

req = Net::HTTP::Post.new(uri)
req.content_type = 'application/json'
req['Accept'] = 'application/json'

# The object won't be serialized exactly like this
# req.body = "{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}"
req.body = {
  'HasExternalDoubleOptIn' => false,
  'Subscribers' => [
    {
      'Name' => 'test1Email',
      'Email' => 'test1@test.com',
      'CustomFields' => [
        'Country=UK'
      ]
    },
    {
      'Name' => 'test2133Email',
      'Email' => 'test2133@test.com',
      'CustomFields' => [
        'Age=25',
        'Country=USA'
      ],
      'Tags' => [
        'repeater'
      ]
    }
  ]
}.to_json

req_options = {
  use_ssl: uri.scheme == 'https'
}
res = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(req)
end
Request
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
)

func main() {
	client := &http.Client{}
	var data = strings.NewReader(`{  
    "HasExternalDoubleOptIn": false,
    "Subscribers":[  
      {  
         "Name":"test1Email",
         "Email":"test1@test.com",
         "CustomFields":[  
            "Country=UK"
         ]
      },
      {  
         "Name":"test2133Email",
         "Email":"test2133@test.com",
         "CustomFields":[  
            "Age=25",
            "Country=USA"
         ],
         "Tags": [
            "repeater"
         ]
      }
   ]
}`)
	req, err := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=", data)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", bodyText)
}
Request
using System.Net.Http;
using System.Net.Http.Headers;

HttpClient client = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=");

request.Headers.Add("Accept", "application/json");

request.Content = new StringContent("{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""HasExternalDoubleOptIn\"": false,
  \""Subscribers\"": [
    {
      \""Name\"": \""test1Email\"",
      \""Email\"": \""test1@test.com\"",
      \""CustomFields\"": [
        \""Country=UK\""
      ]
    },
    {
      \""Name\"": \""test2133Email\"",
      \""Email\"": \""test2133@test.com\"",
      \""CustomFields\"": [
        \""Age=25\"",
        \""Country=USA\""
      ],
            "Tags": [
                "repeater"
            ]
    }
  ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "HasExternalDoubleOptIn": false,
  "Subscribers": [
    {
      "Name": "test1Email",
      "Email": "test1@test.com",
      "CustomFields": [
        "Country=UK"
      ]
    },
    {
      "Name": "test2133Email",
      "Email": "test2133@test.com",
      "CustomFields": [
        "Age=25",
        "Country=USA"
      ],
            "Tags": [
                "repeater"
            ]
    }
  ]
}')
response = client.post( path : "/subscribers/{MailingListID}/subscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
#import <Foundation/Foundation.h>

NSURL *url = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey="];
NSDictionary *headers = @{
    @"Content-Type": @"application/json",
    @"Accept": @"application/json"
};

NSMutableData *data = [[NSMutableData alloc] initWithData:[@"{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:data];

NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"%@", error);
    } else {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSLog(@"%@", httpResponse);
    }
}];
[dataTask resume];
Request
import Foundation

let jsonData = [
    "HasExternalDoubleOptIn": false,
    "Subscribers": [
        [
            "Name": "test1Email",
            "Email": "test1@test.com",
            "CustomFields": [
                "Country=UK"
            ]
        ],
        [
            "Name": "test2133Email",
            "Email": "test2133@test.com",
            "CustomFields": [
                "Age=25",
                "Country=USA"
            ],
            "Tags": [
                "repeater"
            ]
        ]
    ]
] as [String : Any]
let data = try! JSONSerialization.data(withJSONObject: jsonData, options: [])
// let data = "{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}".data(using: .utf8)

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=")!
let headers = [
    "Content-Type": "application/json",
    "Accept": "application/json"
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = data as Data

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print(error)
    } else if let data = data {
        let str = String(data: data, encoding: .utf8)
        print(str ?? "")
    }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": "2 items with invalid email address were ignored: email@email, email2@email",
  "Context": [
    {
      "ID": "ca506fc5-0967-4756-8848-74e9766bdbdd",
      "Name": "test1Email",
      "Email": "test1@test.com",
      "CreatedOn": "/Date(1465377493907+0100)/",
      "UpdatedOn": "/Date(1465381164389)/",
      "UnsubscribedOn": null,
      "UnsubscribedFromID": null,
      "SubscribeType": 1,
      "SubscribeMethod": 1,
      "CustomFields": [
        {
          "CustomFieldID": "42acf2cf-1096-4c80-960b-051791d9a276",
          "Name": "Country",
          "Value": "UK"
        }
      ],
      "RemovedOn": null,
      "Tags": [
            "potential",
            "repeater"
        ]
    },
    {
      "ID": "b751f349-f6b3-4b14-8d75-c37dfafbe40a",
      "Name": "test2133Email",
      "Email": "test2133@test.com",
      "CreatedOn": "/Date(1465377493907+0100)/",
      "UpdatedOn": "/Date(1465381164389)/",
      "UnsubscribedOn": null,
      "UnsubscribedFromID": null,
      "SubscribeType": 1,
      "SubscribeMethod": 1,
      "CustomFields": [
        {
          "CustomFieldID": "60d4e2b0-e5ae-4737-9ac5-ce071ab346fb",
          "Name": "Age",
          "Value": 25
        },
        {
          "CustomFieldID": "42acf2cf-1096-4c80-960b-051791d9a276",
          "Name": "Country",
          "Value": "USA"
        }
      ],
      "RemovedOn": null,
      "Tags": [
            "potential",
            "repeater"
        ]
    }
  ]
}

Update a subscriber

Abstract

Describes the request and response details of this Moosend API endpoint to update a subscriber in your email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the subscriber.

SubscriberID

path

string

true

The ID of the subscriber that you want to update.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account

Name

body

string

false

The name of the subscriber.

Email

body

string

true

The email address of the subscriber.

HasExternalDoubleOptIn

body

Boolean

false

When true, it flags the added subscriber as having given subscription consent by other means.

CustomFields

body

array

false

A list of name-value pairs that match the subscriber’s custom fields defined in the email list.

For example, if you have two custom fields for Age and Country, you must specify the values for these two fields.

Tags

body

object

false

The member tag you can use to filter members by when working with an email list.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the updated subscriber:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=

Request body:
{
  "Name": "Some Name",
  "HasExternalDoubleOptIn": false,
  "Email": "someEmail@email.com",
  "CustomFields": [
    "Age=25",
    "Country=USA",
    "Tags": [
        "repeater"
    ]
  ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\" : \"Some Name\",
    \"HasExternalDoubleOptIn\": false,
    \"Email\" : \"someEmail@email.com\",
    \"CustomFields\": [
        \"Age=25\",
        \"Country=USA\",
    \"Tags\": [
        \"repeater\"
    ]
    ]
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Some Name\",  \"HasExternalDoubleOptIn\": false,  \"Email\": \"someEmail@email.com\",  \"CustomFields\": [    \"Age=25\",    \"Country=USA\"  ],
            "Tags": [
                "repeater"
            ]}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Some Name',
  'HasExternalDoubleOptIn': false,
  'Email': 'someEmail@email.com',
  'CustomFields': [
    'Age=25',
    'Country=USA',
    'Tags': [
      'repeater'
    ]
  ]
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Some Name\",  \"HasExternalDoubleOptIn\": false,  \"Email\": \"someEmail@email.com\",  \"CustomFields\": [    \"Age=25\",    \"Country=USA\"  ],\n    "Tags": [\n        "repeater"\n    ]}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Some Name",  "HasExternalDoubleOptIn": false,  "Email": "someEmail@email.com",  "CustomFields": [    "Age=25",    "Country=USA"  ],
            "Tags": [
                "repeater"
            ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Some Name",
    "HasExternalDoubleOptIn": false,
    "Email": "someEmail@email.com",
    "CustomFields": [
      "Age=25",
      "Country=USA"
    ]
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Some Name\",
  \"HasExternalDoubleOptIn\": false,
  \"Email\": \"someEmail@email.com\",
  \"CustomFields\": [
    \"Age=25\",
    \"Country=USA\",\n    \"Tags\": [\n        \"repeater\"\n    ]
  ]
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Some Name",
  "HasExternalDoubleOptIn": false,
  "Email": "someEmail@email.com",
  "CustomFields": [
    "Age=25",
    "Country=USA",
  'Tags' => [
    'repeater'
  ]
  ]
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Some Name\",\n  \"HasExternalDoubleOptIn\": false,\n  \"Email\": \"someEmail@email.com\",\n  \"CustomFields\": [\n    \"Age=25\",\n    \"Country=USA\"\n  ],
    "Tags": [
        "repeater"
    ]\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Some Name\",  \"HasExternalDoubleOptIn\": false,  \"Email\": \"someEmail@email.com\",  \"CustomFields\": [    \"Age=25\",    \"Country=USA\"  ],\n    \"Tags\": [\n        \"repeater\"\n    ]}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/{MailingListID}/subscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Some Name\"",
  \""HasExternalDoubleOptIn\"": false,
  \""Email\"": \""someEmail@email.com\"",
  \""CustomFields\"": [
    \""Age=25\"",
    \""Country=USA\""
  ],
            "Tags": [
                "repeater"
            ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Some Name",
  "HasExternalDoubleOptIn": false,
  "Email": "someEmail@email.com",
  "CustomFields": [
    "Age=25",
    "Country=USA"
  ],
            "Tags": [
                "repeater"
            ]
}')
response = client.post( path : "/subscribers/{MailingListID}/subscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Some Name\",\n  \"HasExternalDoubleOptIn\": false,\n  \"Email\": \"someEmail@email.com\",\n  \"CustomFields\": [\n    \"Age=25\",\n    \"Country=USA\"\n  ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Some Name\",\n  \"HasExternalDoubleOptIn\": false,\n  \"Email\": \"someEmail@email.com\",\n  \"CustomFields\": [\n    \"Age=25\",\n    \"Country=USA\"\n  ],
    "Tags": [
        "repeater"
    ]\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "d75fca65-a2bc-4474-bd4d-307f9cf63a57",
    "Name": "Some name",
    "Email": "someEmail@email.com",
    "CreatedOn": "/Date(1465380655880+0100)/",
    "UpdatedOn": "/Date(1465388373874)/",
    "UnsubscribedOn": null,
    "UnsubscribedFromID": null,
    "SubscribeType": 1,
    "SubscribeMethod": 2,
    "CustomFields": [
      {
        "CustomFieldID": "b9a6cb39-ec8f-4e5e-a41a-b64b9b3fc190",
        "Name": "Age",
        "Value": 25
      },
      {
        "CustomFieldID": "1c4ff8dc-48e3-4af1-ae4f-2b1b81a44d17",
        "Name": "Country",
        "Value": "USA"
      }
    ],
    "RemovedOn": null,
    "Tags": [
       "potential",
       "repeater"
    ]  
  }
}

Unsubscribe a subscriber from an account

Abstract

Describes the request and response details of this Moosend API endpoint to unsubscribe a subscriber from all email lists in an account.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

body

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=

Request body:
{
  "Email": "test1@test.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Email\":\"test1@test.com\"
}" \
'https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Email\": \"test1@test.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Email': 'test1@test.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Email\": \"test1@test.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Email": "test1@test.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Email": "test1@test.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Email\": \"test1@test.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Email": "test1@test.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Email\": \"test1@test.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Email\": \"test1@test.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Email\"": \""test1@test.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Email": "test1@test.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Email\": \"test1@test.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Email\": \"test1@test.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Unsubscribe a subscriber from a mailing list

Abstract

Describes the request and response details of this Moosend API endpoint to unsubscribe a subscriber from an email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list from which you want to unsubscribe a subscriber.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

body

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=

Request body:
{
  "Email": "test1@test.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Email\":\"test1@test.com\"
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Email\": \"test1@test.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Email': 'test1@test.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Email\": \"test1@test.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Email": "test1@test.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Email": "test1@test.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Email\": \"test1@test.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Email": "test1@test.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Email\": \"test1@test.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Email\": \"test1@test.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Email\"": \""test1@test.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Email": "test1@test.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Email\": \"test1@test.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Email\": \"test1@test.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Unsubscribe a subscriber from a mailing list and a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to unsubscribe a subscriber from an email list and a campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list from which you want to unsubscribe a subscriber.

CampaignID

path

string

true

The ID of the campaign sent to the specific email list.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

body

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=

Request body:
{
  "Email": "test1@test.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Email\":\"test1@test.com\"
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Email\": \"test1@test.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Email': 'test1@test.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Email\": \"test1@test.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Email": "test1@test.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Email": "test1@test.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Email\": \"test1@test.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Email": "test1@test.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Email\": \"test1@test.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Email\": \"test1@test.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Email\"": \""test1@test.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Email": "test1@test.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Email\": \"test1@test.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Email\": \"test1@test.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Remove a subscriber

Abstract

Describes the request and response details of this Moosend API endpoint to remove a subscriber from a specific email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the subscriber you want to remove.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

body

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=

Request body:
{
  "Email": "test1@test.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Email\":\"test1@test.com\"
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Email\": \"test1@test.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Email': 'test1@test.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Email\": \"test1@test.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Email": "test1@test.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Email": "test1@test.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Email\": \"test1@test.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Email": "test1@test.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Email\": \"test1@test.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Email\": \"test1@test.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Email\"": \""test1@test.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Email": "test1@test.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Email\": \"test1@test.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Email\": \"test1@test.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Remove multiple subscribers

Abstract

Describes the request and response details of the Moosend API endpoint to remove multiple subscribers from a specific email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the subscribers you want to remove.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Emails

body

object

true

A list of subscriber email addresses that you want to remove from the email list. Use a comma (,) to separate the email addresses.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains the following information:

    • EmailsIgnored - the number of ignored email addresses.

    • EmailsProcessed - the number of processed email addresses.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=

Request body:
{
  "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{  
   \"Emails\":\"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Emails': 'someEmail@email.com,someEmail2@email.com,someEmail3@email.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Emails\"": \""someEmail@email.com,someEmail2@email.com,someEmail3@email.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "EmailsIgnored": 0,
    "EmailsProcessed": 3
  }
}

Campaigns

Abstract

Describes how to use the Moosend API to get, clone, update, delete, test, and send campaigns, including how to fetch campaign statistics.

Use the Moosend API to fetch your campaigns, get details about campaigns, fetch your campaign senders and their details, create, clone, update, delete, test, and send campaigns. The API also lets you fetch campaign statistics, activity by location, link activity, and campaign summaries.

Get all campaigns by page

Abstract

Describes the request and response details of this Moosend API endpoint to get all campaigns in your account with paging information.

Request

Parameter

In

Type

Required

Description

Page

path

number

false

The page number to display results for.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the information for the requested campaigns:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of campaigns that are included in the response.

      • TotalPageCount - the number of all the available campaign pages for your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • ID - the ID of the campaign.

    • Name - the name of the campaign.

    • Subject - the subject of the campaign.

    • SiteName - the site name of the account.

    • ConfirmationTo - the email address to which a confirmation message is sent when the campaign has been successfully sent.

    • CreatedOn - the date-time the requested campaign was created.

    • ABHoursToTest - specifies the total number of hours to test versions A and B of your campaign before sending the winning version. This is null if the campaign is not an A/B split test campaign.

    • ABCampaignType - specifies the type of the A/B split campaign test. Possible values are:

      • 0 - for a campaign sender test.

      • 1 - for a campaign content test.

      • 2 - for a subject line test.

    • ABWinner - specifies if the winning campaign is A or B. This is null if the campaign is not an A/B split test campaign.

    • ABWinnerSelectionType - specifies the method to determine the winning version for the test. This is null if the given campaign is not an A/B split test campaign, or one of the following values if it is:

      • 0 - the campaign version with the highest number of unique opens is selected to be sent to the rest of your list.

      • 1 - the campaign version with the highest number of unique clicks is selected to be sent to the rest of your list.

    • Status - status of the campaign. Possible values are the following:

      • 0 - draft

      • 1 - queued for sending

      • 3 - sent

      • 4 - not enough credits

      • 5 - awaiting delivery

      • 6 - sending

      • 10 - deleted

      • 11 - selecting a winner

      • 12 - archived

      • 13 - subscription expired

      • 14 - subscription limits exceeded

    • DeliveredOn - the date-time the campaign was delivered.

    • ScheduledFor - the date-time the campaign is scheduled to be delivered.

    • ScheduledForTimezone - the selected time zone for the scheduled campaign to be delivered.

    • CampaignType - the type of campaign which has been created or sent.

      • Regular

      • Digest - Rss or Repeatable

      • Transactional

      • Automation

    • MailingLists - a list of email lists selected for sending the campaign. It contains the following information for each email list:

      • Campaign - the campaign associated with this email list. This is null for this case.

      • MailingList - an object that contains the following information for each email list:

        • ID - the ID of the email list.

        • Name - the name of the email list.

        • ActiveMemberCount - the number of active members in the email list.

        • BouncedMemberCount - the number of bounced emails in the email list.

        • RemovedMemberCount - the number of removed emails in the email list.

        • UnsubscribedMemberCount - the number of unsubscribed emails in the email list.

        • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

        • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list.

        • CreatedBy - the IP address used to create the email list.

        • CreatedOn - the date-time the email list was created.

        • UpdatedBy - the IP address used to update the email list.

        • UpdatedOn - the date-time that the email list was updated.

        • ImportOperation - an object that contains the details of the latest import operation performed in the email list.

      • Segment - a list of segments in the email list containing the following information for each segment. This is null if the campaign was not sent to any email list segment.

        • ID - the ID of the segment.

        • Name - the name of the segment.

        • MatchType - specifies how subscribers are returned by your segment based on matching criteria. Possible values are:

          • 0 - for All. Returns subscribers that match all the given criteria.

          • 1 - for Any. Returns subscribers that match any of the given criteria.

        • Criteria - contains a list with information for each selected criterion selected for the segment.

        • CreatedBy - the IP address used to create the segment.

        • CreatedOn - the date-time the requested segment was created.

        • UpdatedBy - the IP address used to update the segment.

        • UpdatedOn - the date-time the segment was updated.

        • FetchType - the selected fetch type for the selected segment criteria. Possible values are:

          • 0 - for all segment criteria.

          • 1 - for the top segment criteria.

          • 2 - for the top percent segment criteria.

        • Description - contains a string representation of all the selected filters, MatchType criteria, and FetchType criteria.

      • TotalSent - the total number of campaign emails sent.

      • TotalOpens - the total number of emails opens.

      • UniqueOpens - the total number of unique email opens.

      • TotalBounces - the total number of email bounces.

      • TotalForwards - the total number of email forwards for the campaign using the Forward to a friend personalization tag.

      • UniqueForwards - the total number of unique forwards for the campaign using the Forward to a friend personalization tag.

      • TotalLinkClicks - the total number of link clicks.

      • UniqueLinkClicks - the total number of unique link clicks.

      • RecipientsCount - the total number of recipients.

      • IsTransactional - this is false for this case.

      • TotalComplaints - the total number of complaints.

      • TotalUnsubscribes - the total number of unsubscribed recipients for the campaign.

Request
GET https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{Page}.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{Page}.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{Page}.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{Page}.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 10,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": null,
      "SortIsAscending": true
    },
    "Campaigns": [
      {
        "ID": "cbcb297d-52a8-4bed-ae85-640c37c92771",
        "Name": "Test Release 1",
        "Subject": "Test Release 1",
        "SiteName": "mysite",
        "ConfirmationTo": "andreas@email.com",
        "CreatedOn": "/Date(1464952661697+0100)/",
        "ABHoursToTest": null,
        "ABCampaignType": null,
        "ABWinner": null,
        "ABWinnerSelectionType": null,
        "Status": 3,
        "DeliveredOn": "/Date(1464952817450+0100)/",
        "ScheduledFor": null,
        "ScheduledForTimezone": "GTB Standard Time",
        "MailingLists": [
          {
            "Campaign": null,
            "MailingList": {
              "ID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b",
              "Name": "Some Name",
              "ActiveMemberCount": 0,
              "BouncedMemberCount": 0,
              "RemovedMemberCount": 0,
              "UnsubscribedMemberCount": 0,
              "Status": 0,
              "CustomFieldsDefinition": [],
              "CreatedBy": "212.205.224.198",
              "CreatedOn": "/Date(1464952667680+0100)/",
              "UpdatedBy": "212.205.224.198",
              "UpdatedOn": "/Date(1464952667680+0100)/",
              "ImportOperation": null
            },
            "Segment": null
          }
        ],
        "TotalSent": 1,
        "TotalOpens": 1,
        "UniqueOpens": 1,
        "TotalBounces": 0,
        "TotalForwards": 0,
        "UniqueForwards": 0,
        "TotalLinkClicks": 0,
        "UniqueLinkClicks": 0,
        "RecipientsCount": 1,
        "IsTransactional": false,
        "TotalComplaints": 0,
        "TotalUnsubscribes": 0,
        "CampaignSource": null,
        "CampaignType": "Digest"
      },
      {
        "ID": "ef2ab040-aec8-46bf-be54-3d8311093015",
        "Name": "Performance Testing",
        "Subject": "Performance Testing",
        "SiteName": "mysite",
        "ConfirmationTo": "info@northweb.biz",
        "CreatedOn": "/Date(1464647633330+0100)/",
        "ABHoursToTest": null,
        "ABCampaignType": null,
        "ABWinner": null,
        "ABWinnerSelectionType": null,
        "Status": 3,
        "DeliveredOn": "/Date(1464647633207+0100)/",
        "ScheduledFor": null,
        "ScheduledForTimezone": "GTB Standard Time",
        "MailingLists": [
          {
            "Campaign": null,
            "MailingList": {
              "ID": "9b7611be-d395-4677-9983-697d261cca91",
              "Name": "Performance Testing",
              "ActiveMemberCount": 0,
              "BouncedMemberCount": 0,
              "RemovedMemberCount": 0,
              "UnsubscribedMemberCount": 0,
              "Status": 0,
              "CustomFieldsDefinition": [],
              "CreatedBy": "127.0.0.1",
              "CreatedOn": "/Date(1464647633220+0100)/",
              "UpdatedBy": "127.0.0.1",
              "UpdatedOn": "/Date(1464647633220+0100)/",
              "ImportOperation": null
            },
            "Segment": null
          }
        ],
        "TotalSent": 0,
        "TotalOpens": 0,
        "UniqueOpens": 0,
        "TotalBounces": 0,
        "TotalForwards": 0,
        "UniqueForwards": 0,
        "TotalLinkClicks": 0,
        "UniqueLinkClicks": 0,
        "RecipientsCount": 18561,
        "IsTransactional": false,
        "TotalComplaints": 0,
        "TotalUnsubscribes": 0,
        "CampaignSource": null,
        "CampaignType": "Digest"
      }
    ]
  }
}

Get all campaigns by page and page size

Abstract

Describes the request and response details of this Moosend API endpoint to get all campaigns in your account with paging and page size information.

Request

Parameter

In

Type

Required

Description

Page

path

number

false

The page number to display results for. Returns the first page if not specified.

PageSize

path

number

false

The maximum number of results per page. This must be a positive integer up to 1000.

Returns 10 results per page if not specified. If a value greater than 1000 is specified, it is treated as 1000.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

SortBy

query

string

false

The name of the campaign property to sort results by.

Possible values: Name, Subject, Status, DeliveredOn, and CreatedOn (Default).

SortMethod

query

any

false

Specifies the method to sort results.

Possible values: DESC for descending and ASC (Default) for ascending.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the information for the requested campaigns:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of campaigns that are included in the response.

      • TotalPageCount - the number of all the available campaign pages for your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • ID - the ID of the campaign.

    • Name - the name of the campaign.

    • Subject - the subject of the campaign.

    • SiteName - the site name of the account.

    • ConfirmationTo - the email address to which a confirmation message is sent when the campaign has been successfully sent.

    • CreatedOn - the date-time the requested campaign was created.

    • ABHoursToTest - specifies the total number of hours to test versions A and B of your campaign before sending the winning version. This is null if the campaign is not an A/B split test campaign.

    • ABCampaignType - specifies the type of the A/B split campaign test. Possible values are:

      • 0 - for a campaign sender test.

      • 1 - for a campaign content test.

      • 2 - for a subject line test.

    • ABWinner - specifies if the winning campaign is A or B. This is null if the campaign is not an A/B split test campaign.

    • ABWinnerSelectionType - specifies the method to determine the winning version for the test. This is null if the given campaign is not an A/B split test campaign, or one of the following values if it is:

      • 0 - the campaign version with the highest number of unique opens is selected to be sent to the rest of your list.

      • 1 - the campaign version with the highest number of unique clicks is selected to be sent to the rest of your list.

    • Status - status of the campaign. Possible values are the following:

      • 0 - draft

      • 1 - queued for sending

      • 3 - sent

      • 4 - not enough credits

      • 5 - awaiting delivery

      • 6 - sending

      • 10 - deleted

      • 11 - selecting a winner

      • 12 - archived

      • 13 - subscription expired

      • 14 - subscription limits exceeded

    • DeliveredOn - the date-time the campaign was delivered.

    • ScheduledFor - the date-time the campaign is scheduled to be delivered.

    • ScheduledForTimezone - the selected time zone for the scheduled campaign to be delivered.

    • CampaignType - the type of campaign which has been created or sent.

      • Regular

      • Digest - Rss or Repeatable

      • Transactional

      • Automation

    • MailingLists - a list of email lists selected for sending the campaign. It contains the following information for each email list:

      • Campaign - the campaign associated with this email list. This is null for this case.

      • MailingList - an object that contains the following information for each email list:

        • ID - the ID of the email list.

        • Name - the name of the email list.

        • ActiveMemberCount - the number of active members in the email list.

        • BouncedMemberCount - the number of bounced emails in the email list.

        • RemovedMemberCount - the number of removed emails in the email list.

        • UnsubscribedMemberCount - the number of unsubscribed emails in the email list.

        • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

        • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list.

        • CreatedBy - the IP address used to create the email list.

        • CreatedOn - the date-time the email list was created.

        • UpdatedBy - the IP address used to update the email list.

        • UpdatedOn - the date-time that the email list was updated.

        • ImportOperation - an object that contains the details of the latest import operation performed in the email list.

      • Segment - a list of segments in the email list containing the following information for each segment. This is null if the campaign was not sent to any email list segment.

        • ID - the ID of the segment.

        • Name - the name of the segment.

        • MatchType - specifies how subscribers are returned by your segment based on matching criteria. Possible values are:

          • 0 - for All. Returns subscribers that match all the given criteria.

          • 1 - for Any. Returns subscribers that match any of the given criteria.

        • Criteria - contains a list with information for each selected criterion selected for the segment.

        • CreatedBy - the IP address used to create the segment.

        • CreatedOn - the date-time the requested segment was created.

        • UpdatedBy - the IP address used to update the segment.

        • UpdatedOn - the date-time the segment was updated.

        • FetchType - the selected fetch type for the selected segment criteria. Possible values are:

          • 0 - for all segment criteria.

          • 1 - for the top segment criteria.

          • 2 - for the top percent segment criteria.

        • Description - contains a string representation of all the selected filters, MatchType criteria, and FetchType criteria.

      • TotalSent - the total number of campaign emails sent.

      • TotalOpens - the total number of emails opens.

      • UniqueOpens - the total number of unique email opens.

      • TotalBounces - the total number of email bounces.

      • TotalForwards - the total number of email forwards for the campaign using the Forward to a friend personalization tag.

      • UniqueForwards - the total number of unique forwards for the campaign using the Forward to a friend personalization tag.

      • TotalLinkClicks - the total number of link clicks.

      • UniqueLinkClicks - the total number of unique link clicks.

      • RecipientsCount - the total number of recipients.

      • IsTransactional - this is false for this case.

      • TotalComplaints - the total number of complaints.

      • TotalUnsubscribes - the total number of unsubscribed recipients for the campaign.

Request
GET https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=
Request
curl --include \
'https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>dependencies

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 5,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": null,
      "SortIsAscending": true
    },
    "Campaigns": [
      {
        "ID": "cbcb297d-52a8-4bed-ae85-640c37c92771",
        "Name": "Test Release 1",
        "Subject": "Test Release 1",
        "SiteName": "mysite",
        "ConfirmationTo": "andreas@email.com",
        "CreatedOn": "/Date(1464952661697+0100)/",
        "ABHoursToTest": null,
        "ABCampaignType": null,
        "ABWinner": null,
        "ABWinnerSelectionType": null,
        "Status": 3,
        "DeliveredOn": "/Date(1464952817450+0100)/",
        "ScheduledFor": null,
        "ScheduledForTimezone": "GTB Standard Time",
        "MailingLists": [
          {
            "Campaign": null,
            "MailingList": {
              "ID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b",
              "Name": "Some Name",
              "ActiveMemberCount": 0,
              "BouncedMemberCount": 0,
              "RemovedMemberCount": 0,
              "UnsubscribedMemberCount": 0,
              "Status": 0,
              "CustomFieldsDefinition": [],
              "CreatedBy": "212.205.224.198",
              "CreatedOn": "/Date(1464952667680+0100)/",
              "UpdatedBy": "212.205.224.198",
              "UpdatedOn": "/Date(1464952667680+0100)/",
              "ImportOperation": null
            },
            "Segment": null
          }
        ],
        "TotalSent": 1,
        "TotalOpens": 1,
        "UniqueOpens": 1,
        "TotalBounces": 0,
        "TotalForwards": 0,
        "UniqueForwards": 0,
        "TotalLinkClicks": 0,
        "UniqueLinkClicks": 0,
        "RecipientsCount": 1,
        "IsTransactional": false,
        "TotalComplaints": 0,
        "TotalUnsubscribes": 0,
        "CampaignSource": null,
        "CampaignType": "Digest"
      },
      {
        "ID": "ef2ab040-aec8-46bf-be54-3d8311093015",
        "Name": "Performance Testing",
        "Subject": "Performance Testing",
        "SiteName": "mysite",
        "ConfirmationTo": "info@northweb.biz",
        "CreatedOn": "/Date(1464647633330+0100)/",
        "ABHoursToTest": null,
        "ABCampaignType": null,
        "ABWinner": null,
        "ABWinnerSelectionType": null,
        "Status": 3,
        "DeliveredOn": "/Date(1464647633207+0100)/",
        "ScheduledFor": null,
        "ScheduledForTimezone": "GTB Standard Time",
        "MailingLists": [
          {
            "Campaign": null,
            "MailingList": {
              "ID": "9b7611be-d395-4637-9983-697d261cca91",
              "Name": "Performance Testing",
              "ActiveMemberCount": 0,
              "BouncedMemberCount": 0,
              "RemovedMemberCount": 0,
              "UnsubscribedMemberCount": 0,
              "Status": 0,
              "CustomFieldsDefinition": [],
              "CreatedBy": "127.0.0.1",
              "CreatedOn": "/Date(1464647633220+0100)/",
              "UpdatedBy": "127.0.0.1",
              "UpdatedOn": "/Date(1464647633220+0100)/",
              "ImportOperation": null
            },
            "Segment": null
          }
        ],
        "TotalSent": 0,
        "TotalOpens": 0,
        "UniqueOpens": 0,
        "TotalBounces": 0,
        "TotalForwards": 0,
        "UniqueForwards": 0,
        "TotalLinkClicks": 0,
        "UniqueLinkClicks": 0,
        "RecipientsCount": 18561,
        "IsTransactional": false,
        "TotalComplaints": 0,
        "TotalUnsubscribes": 0,
        "CampaignSource": null,
        "CampaignType": "Digest"
      }
    ]
  }
}

Get campaign details

Abstract

Describes the request and response details of this Moosend API endpoint to get details of a specific campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that contains the details you are requesting.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested campaign:

  • ID - the ID of the campaign.

  • Name - the name of the campaign.

  • Subject - the subject of the campaign.

  • WebLocation - the web location of the HTML campaign.

  • HTMLContent - the HTML content of the campaign.

  • PlainContent - the content of the campaign in plain text.

  • Sender - a list that contains the following information about the campaign sender:

    • ID - the ID of the sender.

    • Name - the name of the sender.

    • Email - the email address of the sender.

    • CreatedOn - the date that the sender was created.

    • IsEnabled - this is true if the sender is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the sender is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the sender is enabled and false if it is not.

    • DkimPublic - specifies the sender's email public DKIM.

  • DeliveredOn - the date-time the campaign was delivered. This is null for a cloned campaign.

  • ReplyToEmail - an object that contains details about the Reply to email address selected to receive replies from the campaign:

    • ID - the ID of the Reply to email receiver.

    • Name - the name of the Reply to email receiver.

    • Email - the email address of the Reply to email receiver.

    • CreatedOn - the date that the Reply to email receiver was created.

    • IsEnabled - this is true if the Reply to email receiver is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the Reply to email receiver is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the Reply to email receiver is enabled and false if it is not.

    • DkimPublic - specifies the Reply to email receiver's email public DKIM.

  • CreatedOn - the date-time the campaign was created.

  • UpdatedOn - the date-time the campaign was updated.

  • ScheduledFor - the date-time the campaign is scheduled to be delivered. This is null for a cloned campaign.

  • TimeZone - the selected time zone for the account.

  • FormatType - the format type of the campaign. This is 0 for HTML, 1 for Template, and 2 for Plain Text.

  • ABCampaignData - this is null if the campaign is a regular campaign. If the campaign is an A/B split campaign, the object contains the following information :

    • ID - the four-digit integer ID of the ABCampaignData.

    • SubjectB - if the A/B split campaign is testing the subject, this is the subject line for campaign B.

    • PlainContentB - if the A/B split campaign is testing the content, this is the plain text content for campaign B.

    • HTMLContentB - if the A/B split campaign is testing the content, this is the HTML content for campaign B.

    • WebLocationB - if the A/B split campaign is testing the content, this is the web location for campaign B.

    • SenderB - if the A/B split campaign is testing the sender, this is campaign B's sender.

    • HoursToTest - the total number of hours to test campaigns A and B of your split test before sending the winning version.

    • ListPercentage - specifies the size of your test group in your list.

    • ABCampaignType - specifies the type of A/B split campaign. This is 0 for sender, 1 for content, and 2 for subject line

    • ABWinnerSelectionType - specifies the type of test that defines the winning version of the campaign. This is 0 for a unique opens test and 1 for a unique clicks test.

    • DeliveredOnA - the date-time campaign A was delivered. This is null for a cloned campaign.

    • DeliveredOnB - the date-time campaign B was delivered. This is null for a cloned campaign.

  • MailingLists - a list that contains the email lists or segments that that campaign is sent to.

    • MailingListID - the ID of the email list.

    • SegmentID - the ID of the selected segment. This is 0 if there is no segment selected.

  • ConfirmationTo - the email address to which a confirmation message is sent when the campaign has been successfully sent.

  • Status - status of the campaign.

  • IsTransactional - specifies whether the campaign was created using SMTP. This can be true or false.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "2fa129d1-a0ab-467a-ab3e-e43fd9f6bfb",
    "Name": "Test",
    "Subject": "Test",
    "WebLocation": null,
    "HTMLContent": someHtmlContent,
    "PlainContent": somePlainContent,
    "Sender": {
      "ID": "28a7ee75-034a-44e0-a946-fe28fc229d6e",
      "Name": "Fanis",
      "Email": "some@memail.com",
      "CreatedOn": "/Date(1457684250090+0100)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": true,
      "DkimPublic": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmO"
    },
    "DeliveredOn": "/Date(1464339959683+0100)/",
    "ReplyToEmail": {
      "ID": "28a7ee75-034a-4110-a9116-fe34235re6e",
      "Name": "Fanis",
      "Email": "some@email.com",
      "CreatedOn": "/Date(1457684250090+0100)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": true,
      "DkimPublic": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmO"
    },
    "CreatedOn": "/Date(1464339921630+0100)/",
    "UpdatedOn": "/Date(1464339949343+0100)/",
    "ScheduledFor": null,
    "Timezone": "GTB Standard Time",
    "FormatType": 0,
    "ABCampaignData": null,
    "MailingLists": [
      {
        "MailingListID": "ad4b18-3sd0-4e1a-a110-481080fa94",
        "SegmentID": 0
      }
    ],
    "ConfirmationTo": "some@email.com",
    "Status": 3,
    "IsTransactional": false
  }
}

Get all senders

Abstract

Describes the request and response details of this Moosend API endpoint to get senders of a specific campaign.

Request

Parameter

In

Type

Required

Description

Format

path

string

true

The supported file format for getting a response.

Possible values: jsonand xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code for this call. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - a list of campaign senders in your account containing the following information for each sender:

    • ID - the ID of the sender.

    • Name - the name of the sender.

    • Email - the email address of the sender.

    • CreatedOn - the date that the sender was created.

    • IsEnabled - this is true if the sender is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the sender is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the sender is enabled and false if it is not.

    • DkimPublic - specifies the sender's email public DKIM.

Request
GET https://{hostname}/v3/senders/find_all.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/senders/find_all.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/senders/find_all.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/senders/find_all.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/senders/find_all.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/senders/find_all.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/senders/find_all.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/senders/find_all.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/senders/find_all.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/senders/find_all.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/senders/find_all.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/senders/find_all.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/senders/find_all.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/senders/find_all.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/senders/find_all.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": [
    {
      "ID": "01234567-89ab-cdef-0123-456789abcdef",
      "Name": "Your Name",
      "Email": "sender@example.com",
      "CreatedOn": "/Date(1323857838000+0200)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": false,
      "DkimPublic": "Some DkimPublic"
    },
    {
      "ID": "e57c96b7-5786-489b-b3a2-bac3e30dd6bd",
      "Name": "Some Name",
      "Email": "Some Email",
      "CreatedOn": "/Date(1400765125478)/",
      "IsEnabled": false,
      "SpfVerified": false,
      "DkimVerified": false,
      "DkimPublic": "Some DkimPublic"
    }
  ]
}

Get sender details

Abstract

Describes the request and response details of this Moosend API endpoint to get details of a specific sender.

Request

Parameter

In

Type

Required

Description

Format

path

string

true

The supported file format for getting a response.

Possible values: jsonand xml.

Email

query

string

true

The email address of the sender that contains the details you are requesting.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the information about the sender:

    • ID - the ID of the sender.

    • Name - the name of the sender.

    • Email - the email address of the sender.

    • CreatedOn - the date that the sender was created.

    • IsEnabled - this is true if the sender is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the sender is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the sender is enabled and false if it is not.

    • DkimPublic - specifies the sender's email public DKIM.

Request
GET https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=
Request
curl --include \
'https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}v/v3/senders/find_one.{Format}?Email=&apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/senders/find_all.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/senders/find_all.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "01234567-89ab-cdef-0123-456789abcdef",
    "Name": "Your Name",
    "Email": "sender@example.com",
    "CreatedOn": "/Date(1323857838000+0200)/",
    "IsEnabled": true,
    "SpfVerified": false,
    "DkimVerified": false,
    "DkimPublic": "Some DkimPublic"
  }
}

Create a draft campaign

Abstract

Describes the request and response details of this Moosend API endpoint to create a draft campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the campaign.

Subject

body

string

true

The subject line of the campaign.

SenderEmail

body

string

true

The email address of the campaign sender.

ReplyToEmail

body

string

true

The email address selected to receive replies from the campaign. This must be one of your campaign senders. If not specified, the SenderEmail is assumed.

ConfirmationToEmail

body

string

false

The email address used to send a confirmation message when the campaign has been successfully sent. This can be any valid email address. If not specified, the SenderEmail is assumed.

HTMLContent

body

string

false

The complete HTML body of the campaign. You can use this parameter instead of using the WebLocation parameter.

WebLocation

body

string

false

The URL used to retrieve the HTML content of the campaign. Moosend automatically moves all CSS inline.

MailingLists

body

array

false

A list of email lists in your account that is used to send the campaign.

SegmentID

body

string

false

The ID of a segment in the selected email list. If not specified, the campaign is sent to all active subscribers of the email list.

IsAB

body

Boolean

true

A flag that defines if a campaign is an A/B split campaign. If true, you must fill out A/B split campaign parameters.

TrackInGoogleAnalytics

body

Boolean

false

Specifies if tracking is enabled for the campaign. You must have Google Analytics configured on your site to use this feature.

A/B split campaign parameters

Use these parameters when creating an A/B split campaign. If you specify any of the parameters below when creating a regular campaign, they are ignored in the request.

Parameter

In

Type

Required

Description

ABCampaignType

body

string

true

Specify the type of test to be performed in the AB split campaign to determine the winning version:

  • Subjectline - test two different versions of the subject line.

  • Content - test two different versions of the campaign content.

  • Sender - test two different versions of the campaign sender.

SubjectB

body

string

false

If testing A/B split campaigns with two subject line versions, this is the second subject version of the subject.

HTMLContentB

body

string

false

If testing A/B split campaigns with two HTML content versions, this is the complete HTML body of the second version.

WebLocationB

body

string

false

If testing A/B split campaigns with two HTML content versions, this is the web location of the second HTML content version.

SenderEmailB

body

string

false

If testing A/B split campaigns with two sender versions, this is the email address of the second campaign sender. This must be one of the senders defined in your account.

HoursToTest

body

integer

false

Specify how long the test runs, before determining the winning campaign version to be sent to the rest of the recipients.

This must be an integer between 1 and 24.

ListPercentage

body

integer

false

Specifies a portion of the target recipients to get the test campaign versions. For example, if you specify 10, then 10% of your recipients receive campaign A and another 10% receive the campaign B version.

This must be an integer between 5 and 40.

ABWinnerSelectionType

body

string

false

Specifies the method to determine the winning version for the test. If not set, OpenRate is assumed.

  • OpenRate - determine the winner based on the version that achieved more opens.

  • TotalUniqueClicks - determine the winner based on the version that achieved more unique link clicks.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the campaign created.

Request
POST https://{hostname}/v3/campaigns/create.{Format}?apikey=

Request body:
{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "HTMLContent": "Some HTML body",  
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"Test campaign\",
    \"Subject\":\"Some subject\",
    \"SenderEmail\":\"something@email.com\",
    \"ReplyToEmail\":\"something@email.com\",
    \"ConfirmationToEmail\":\"something@email.com\",
    \"HTMLContent\":\"Some HTML body\",      
    \"MailingLists\": [
        {
            \"MailingListID\":\"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
            \"SegmentID\":\"10166\"
        },
        {
            \"MailingListID\":\"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
        }
    ],
    \"IsAB\":\"true\",
    \"ABCampaignType\":\"Content\",
    \"WebLocationB\":\"http://www.mysite.gr/newsletter/index\",
    \"HoursToTest\":\"2\",
    \"ListPercentage\":\"20\",
    \"ABWinnerSelectionType\":\"OpenRate\"
}" \
'https://{hostname}/v3/campaigns/create.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"HTMLContent\": \"Some HTML body\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}");
Response response = client.target("https://{hostname}/v3/campaigns/create.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/create.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Test campaign',
  'Subject': 'Some subject',
  'SenderEmail': 'something@email.com',
  'ReplyToEmail': 'something@email.com',
  'ConfirmationToEmail': 'something@email.com',
  'HTMLContent': 'Some HTML body',  
  'MailingLists': [
    {
      'MailingListID': 'adaf2fe1-55db-42dc-aaf8-56d8f502138d',
      'SegmentID': '10166'
    },
    {
      'MailingListID': 'dce99b7a-2619-4805-aaeb-7fecdcb3c71b'
    }
  ],
  'IsAB': 'true',
  'ABCampaignType': 'Content',
  'WebLocationB': 'http://www.mysite.gr/newsletter/index',
  'HoursToTest': '2',
  'ListPercentage': '20',
  'ABWinnerSelectionType': 'OpenRate'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/create.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"HTMLContent\": \"Some HTML body\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Test campaign",  "Subject": "Some subject",  "SenderEmail": "something@email.com",  "ReplyToEmail": "something@email.com",  "ConfirmationToEmail": "something@email.com",  "HTMLContent": "Some HTML body",  "MailingLists": [    {      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",      "SegmentID": "10166"    },    {      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"    }  ],  "IsAB": "true",  "ABCampaignType": "Content",  "WebLocationB": "http://www.mysite.gr/newsletter/index",  "HoursToTest": "2",  "ListPercentage": "20",  "ABWinnerSelectionType": "OpenRate"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/campaigns/create.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Test campaign",
    "Subject": "Some subject",
    "SenderEmail": "something@email.com",
    "ReplyToEmail": "something@email.com",
    "ConfirmationToEmail": "something@email.com",
    "HTMLContent": "Some HTML body", 
    "MailingLists": [
      {
        "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
        "SegmentID": "10166"
      },
      {
        "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
      }
    ],
    "IsAB": "true",
    "ABCampaignType": "Content",
    "WebLocationB": "http://www.mysite.gr/newsletter/index",
    "HoursToTest": "2",
    "ListPercentage": "20",
    "ABWinnerSelectionType": "OpenRate"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/campaigns/create.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/create.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Test campaign\",
  \"Subject\": \"Some subject\",
  \"SenderEmail\": \"something@email.com\",
  \"ReplyToEmail\": \"something@email.com\",
  \"ConfirmationToEmail\": \"something@email.com\",
  \"HTMLContent\": \"Some HTML body\", 
  \"MailingLists\": [
    {
      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
      \"SegmentID\": \"10166\"
    },
    {
      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
    }
  ],
  \"IsAB\": \"true\",
  \"ABCampaignType\": \"Content\",
  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",
  \"HoursToTest\": \"2\",
  \"ListPercentage\": \"20\",
  \"ABWinnerSelectionType\": \"OpenRate\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "HTMLContent": "Some HTML body",
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/campaigns/create.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"HTMLContent\": \"Some HTML body\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/create.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"HTMLContent\": \"Some HTML body\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/clone.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/create.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Test campaign\"",
  \""Subject\"": \""Some subject\"",
  \""SenderEmail\"": \""something@email.com\"",
  \""ReplyToEmail\"": \""something@email.com\"",
  \""ConfirmationToEmail\"": \""something@email.com\"",
  \""HTMLContent\"": \""Some HTML body\"", 
  \""MailingLists\"": [
    {
      \""MailingListID\"": \""adaf2fe1-55db-42dc-aaf8-56d8f502138d\"",
      \""SegmentID\"": \""10166\""
    },
    {
      \""MailingListID\"": \""dce99b7a-2619-4805-aaeb-7fecdcb3c71b\""
    }
  ],
  \""IsAB\"": \""true\"",
  \""ABCampaignType\"": \""Content\"",
  \""WebLocationB\"": \""http://www.mysite.gr/newsletter/index\"",
  \""HoursToTest\"": \""2\"",
  \""ListPercentage\"": \""20\"",
  \""ABWinnerSelectionType\"": \""OpenRate\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "HTMLContent": "Some HTML body",  
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}')
response = client.post( path : "/campaigns/{CampaignID}/clone.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/create.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"HTMLContent\": \"Some HTML body\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/create.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"HTMLContent\": \"Some HTML body\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "afdc4ef6-999f-4d74-905b-ec234789f9d6"
}

Manage a transactional campaign

Abstract

Describes the request and response details of this Moosend API endpoint to create a transactional campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

apikey

query

string

true

The API key of your account.

From

body

object

false

An array containing the parameters of the sender:

Email - the email address of a verified sender.

sendersName - the name of the sender name displayed in the recipient's inbox.

ReplyTo

body

object

false

An array containing the parameters of the sender the user can reply to:

Email - the email address of one of a verified sender.

sendersName - the name of the Reply to email displayed to the user when the user clicks Reply.

Subject

body

string

true

The subject line of the email message displayed to the recipient. It may contain parameters for personalization. When no value is provided, use the subject of the template.

TemplateId

body

GUID

false

Statistics will be registered to the campaign with this ID. If you have created a template id, you can find it in the user interface.

If the array content is empty or doesn’t exist, then the content for the email is taken from the template id provided.

TemplateName

body

string

false

The name of the transactional campaign that this message will be sent for. Transactional campaign names are unique.

If the array content is empty or doesn’t exist, then the content for the email is taken from the template name provided.

Content

body

array

false

Content types:

Type - the type of content to send.

Value - the format specified by content.type. It may contain parameters to be substituted for each recipient, according to the parameters given in the personalization property.

WebLocation - the URL that holds the content to use for this this message. To reuse it for the next requests and avoid re-downloading, cache it to S3 for 24 hours.

Only one content should exist in the payload for the call to be valid. If there is a content and template ID or name, then the content overrules and the template ID is kept to show the location of the statistics.

Personalizations

body

array

true

A list of recipients of the transactional message. It may contain personalization parameters.

To - an array containing the parameters of the receiver

Email - the recipient email address (text/plain).

Name - the recipient name (text/plain).

Substitutions - the values to substitute in the message content/subject for the current recipient, in the form of key/value pairs.

MailSettings

body

array

true

When set to true or omitted, the message will be delivered to the recipient, even if they have unsubscribed from the transactional email list.

Default: true

BypassUnsubscribeManagement

Enable - true (default) / false

attachments

body

object

false

An array containing the parameters of the attachments: -

Content - A base64 string that represents the file bytes of the attachment (Required).

Type - The MIME type of the attached content (e.g. application/pdf, image/PNG) (Required).

FileName - The file name of the attachment that the recipient will see (Required).

Disposition - Allowed values are: “inline”, “attachment” (Required).

ContentId - A user-defined string that maps an embedded image to an attachment. (Required only for inline disposition).

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

Request
POST /v3/campaigns/transactional/send.json?apikey= HTTP/1.1
Host: {hostname}
Content-Type: application/json
Content-Length: 2165

{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}
Request
curl --location --globoff '{hostname}/v3/campaigns/transactional/send.json?apikey=' \
--header 'Content-Type: application/json' \
--data-raw '{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}'
Request
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("http://{hostname}/v3/campaigns/transactional/send.json?apikey="))
    .POST(BodyPublishers.ofString("{ \n    \"From\": { \n        \"Email\": \"orders@example.com\", \n        \"Name\": \"Example Order Confirmation\" \n    }, \n    \"ReplyTo\": { \n        \"Email\": \"customer_service@example.com\", \n        \"Name\": \"Example Customer Service Team\" \n    }, \n    \"Subject\": \"Your Example Order Confirmation\", \n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \n    \"TemplateName\": \"My Sending Template\", \n    \"Content\": [ \n        { \n            \"Type\": \"text/html\", \n            \"Value\": \"<p>Hello world</p>\", \n            \"WebLocation\": \"https://mycompany.com/template.html\" \n        } \n    ], \n    \"Personalizations\": [ \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"john_doe@example.com\", \n                    \"Name\": \"John Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        }, \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"julia_doe@example.com\", \n                    \"Name\": \"Julia Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        } \n    ], \n    \"MailSettings\": { \n        \"BypassUnsubscribeManagement\": { \n            \"Enable\": true \n        } \n    },\n  \"attachments\": [\n    {\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"Type\": \"application/pdf\",\n      \"FileName\": \"attachementexample.pdf\",\n      \"disposition\": \"attachment\",\n      \"ContentId\": \"attachment-a\"\n    },\n    {\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"type\": \"image/PNG\",\n      \"filename\": \"imageexample.png\",\n      \"disposition\": \"inline\",\n      \"contentId\": \"image-a\"\n    }\n  ]\n}"))
    .setHeader("Content-Type", "application/json")
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Request
var settings = {
  "url": "{hostname}/v3/campaigns/transactional/send.json?apikey=",
  "method": "POST",
  "timeout": 0,
  "headers": {
    "Content-Type": "application/json"
  },
  "data": JSON.stringify({
    "From": {
      "Email": "orders@example.com",
      "Name": "Example Order Confirmation"
    },
    "ReplyTo": {
      "Email": "customer_service@example.com",
      "Name": "Example Customer Service Team"
    },
    "Subject": "Your Example Order Confirmation",
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
    "TemplateName": "My Sending Template",
    "Content": [
      {
        "Type": "text/html",
        "Value": "<p>Hello world</p>",
        "WebLocation": "https://mycompany.com/template.html"
      }
    ],
    "Personalizations": [
      {
        "To": [
          {
            "Email": "john_doe@example.com",
            "Name": "John Doe"
          }
        ],
        "Substitutions": {
          "key1": "value1",
          "key2": "value2"
        }
      },
      {
        "To": [
          {
            "Email": "julia_doe@example.com",
            "Name": "Julia Doe"
          }
        ],
        "Substitutions": {
          "key1": "value1",
          "key2": "value2"
        }
      }
    ],
    "MailSettings": {
      "BypassUnsubscribeManagement": {
        "Enable": true
      }
    },
    "attachments": [
      {
        "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
        "Type": "application/pdf",
        "FileName": "attachementexample.pdf",
        "disposition": "attachment",
        "ContentId": "attachment-a"
      },
      {
        "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
        "type": "image/PNG",
        "filename": "imageexample.png",
        "disposition": "inline",
        "contentId": "image-a"
      }
    ]
  }),
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
Request
var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'POST',
  'hostname': '{hostname}',
  'path': '/v3/campaigns/transactional/send.json?apikey=',
  'headers': {
    'Content-Type': 'application/json'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = JSON.stringify({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": true
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
});

req.write(postData);

req.end();
Request
use LWP::UserAgent;

$ua = LWP::UserAgent->new();
$response = $ua->post(
    'http://{hostname}/v3/campaigns/transactional/send.json?apikey=',
    'Content-Type' => 'application/json',
    Content => "{ \n    \"From\": { \n        \"Email\": \"orders\@example.com\", \n        \"Name\": \"Example Order Confirmation\" \n    }, \n    \"ReplyTo\": { \n        \"Email\": \"customer_service\@example.com\", \n        \"Name\": \"Example Customer Service Team\" \n    }, \n    \"Subject\": \"Your Example Order Confirmation\", \n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \n    \"TemplateName\": \"My Sending Template\", \n    \"Content\": [ \n        { \n            \"Type\": \"text/html\", \n            \"Value\": \"<p>Hello world</p>\", \n            \"WebLocation\": \"https://mycompany.com/template.html\" \n        } \n    ], \n    \"Personalizations\": [ \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"john_doe\@example.com\", \n                    \"Name\": \"John Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        }, \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"julia_doe\@example.com\", \n                    \"Name\": \"Julia Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        } \n    ], \n    \"MailSettings\": { \n        \"BypassUnsubscribeManagement\": { \n            \"Enable\": true \n        } \n    },\n  \"attachments\": [\n    {\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"Type\": \"application/pdf\",\n      \"FileName\": \"attachementexample.pdf\",\n      \"disposition\": \"attachment\",\n      \"ContentId\": \"attachment-a\"\n    },\n    {\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"type\": \"image/PNG\",\n      \"filename\": \"imageexample.png\",\n      \"disposition\": \"inline\",\n      \"contentId\": \"image-a\"\n    }\n  ]\n}"
);
Request
import http.client
import json

conn = http.client.HTTPSConnection("{hostname}")
payload = json.dumps({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": True
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
})
headers = {
  'Content-Type': 'application/json'
}
conn.request("POST", "/v3/campaigns/transactional/send.json?apikey=", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Request
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => '{hostname}/v3/campaigns/transactional/send.json?apikey=',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Request
require "uri"
require "json"
require "net/http"

url = URI("{hostname}/v3/campaigns/transactional/send.json?apikey=")

http = Net::HTTP.new(url.host, url.port);
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request.body = JSON.dump({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": true
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
})

response = http.request(request)
puts response.read_body

Request
 package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "{hostname}/v3/campaigns/transactional/send.json?apikey="
  method := "POST"

  payload := strings.NewReader(`{ `+"
"+`
    "From": { `+"
"+`
        "Email": "orders@example.com", `+"
"+`
        "Name": "Example Order Confirmation" `+"
"+`
    }, `+"
"+`
    "ReplyTo": { `+"
"+`
        "Email": "customer_service@example.com", `+"
"+`
        "Name": "Example Customer Service Team" `+"
"+`
    }, `+"
"+`
    "Subject": "Your Example Order Confirmation", `+"
"+`
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", `+"
"+`
    "TemplateName": "My Sending Template", `+"
"+`
    "Content": [ `+"
"+`
        { `+"
"+`
            "Type": "text/html", `+"
"+`
            "Value": "<p>Hello world</p>", `+"
"+`
            "WebLocation": "https://mycompany.com/template.html" `+"
"+`
        } `+"
"+`
    ], `+"
"+`
    "Personalizations": [ `+"
"+`
        { `+"
"+`
            "To": [ `+"
"+`
                { `+"
"+`
                    "Email": "john_doe@example.com", `+"
"+`
                    "Name": "John Doe" `+"
"+`
                } `+"
"+`
            ], `+"
"+`
            "Substitutions": { `+"
"+`
                    "key1": "value1", `+"
"+`
                    "key2": "value2" `+"
"+`
                } `+"
"+`
        }, `+"
"+`
        { `+"
"+`
            "To": [ `+"
"+`
                { `+"
"+`
                    "Email": "julia_doe@example.com", `+"
"+`
                    "Name": "Julia Doe" `+"
"+`
                } `+"
"+`
            ], `+"
"+`
            "Substitutions": { `+"
"+`
                    "key1": "value1", `+"
"+`
                    "key2": "value2" `+"
"+`
                } `+"
"+`
        } `+"
"+`
    ], `+"
"+`
    "MailSettings": { `+"
"+`
        "BypassUnsubscribeManagement": { `+"
"+`
            "Enable": true `+"
"+`
        } `+"
"+`
    },`+"
"+`
  "attachments": [`+"
"+`
    {`+"
"+`
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",`+"
"+`
      "Type": "application/pdf",`+"
"+`
      "FileName": "attachementexample.pdf",`+"
"+`
      "disposition": "attachment",`+"
"+`
      "ContentId": "attachment-a"`+"
"+`
    },`+"
"+`
    {`+"
"+`
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",`+"
"+`
      "type": "image/PNG",`+"
"+`
      "filename": "imageexample.png",`+"
"+`
      "disposition": "inline",`+"
"+`
      "contentId": "image-a"`+"
"+`
    }`+"
"+`
  ]`+"
"+`
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
Request
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "{hostname}/v3/campaigns/transactional/send.json?apikey=");
var content = new StringContent("{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
Request
#import <Foundation/Foundation.h>

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"%7Bhostname%7D/v3/campaigns/transactional/send.json?apikey="]
  cachePolicy:NSURLRequestUseProtocolCachePolicy
  timeoutInterval:10.0];
NSDictionary *headers = @{
  @"Content-Type": @"application/json"
};

[request setAllHTTPHeaderFields:headers];
NSData *postData = [[NSData alloc] initWithData:[@"{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];

[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  if (error) {
    NSLog(@"%@", error);
    dispatch_semaphore_signal(sema);
  } else {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSError *parseError = nil;
    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    NSLog(@"%@",responseDictionary);
    dispatch_semaphore_signal(sema);
  }
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
Request
let parameters = "{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}"
let postData = parameters.data(using: .utf8)

var request = URLRequest(url: URL(string: "{hostname}/v3/campaigns/transactional/send.json?apikey=")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
  guard let data = data else {
    print(String(describing: error))
    return
  }
  print(String(data: data, encoding: .utf8)!)
}

task.resume()
Request
POST /v3/campaigns/transactional/send.json?apikey= HTTP/1.1
Host: {hostname}
Content-Type: application/json
Content-Length: 2165

{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}
Request
POST /v3/campaigns/transactional/send.json?apikey= HTTP/1.1
Host: {hostname}
Content-Type: application/json
Content-Length: 2165

{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}
Request
curl --location --globoff '{hostname}/v3/campaigns/transactional/send.json?apikey=' \
--header 'Content-Type: application/json' \
--data-raw '{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}'
Request
curl --location --globoff '{hostname}/v3/campaigns/transactional/send.json?apikey=' \
--header 'Content-Type: application/json' \
--data-raw '{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}'
Request
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("http://{hostname}/v3/campaigns/transactional/send.json?apikey="))
    .POST(BodyPublishers.ofString("{ \n    \"From\": { \n        \"Email\": \"orders@example.com\", \n        \"Name\": \"Example Order Confirmation\" \n    }, \n    \"ReplyTo\": { \n        \"Email\": \"customer_service@example.com\", \n        \"Name\": \"Example Customer Service Team\" \n    }, \n    \"Subject\": \"Your Example Order Confirmation\", \n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \n    \"TemplateName\": \"My Sending Template\", \n    \"Content\": [ \n        { \n            \"Type\": \"text/html\", \n            \"Value\": \"<p>Hello world</p>\", \n            \"WebLocation\": \"https://mycompany.com/template.html\" \n        } \n    ], \n    \"Personalizations\": [ \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"john_doe@example.com\", \n                    \"Name\": \"John Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        }, \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"julia_doe@example.com\", \n                    \"Name\": \"Julia Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        } \n    ], \n    \"MailSettings\": { \n        \"BypassUnsubscribeManagement\": { \n            \"Enable\": true \n        } \n    },\n  \"attachments\": [\n    {\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"Type\": \"application/pdf\",\n      \"FileName\": \"attachementexample.pdf\",\n      \"disposition\": \"attachment\",\n      \"ContentId\": \"attachment-a\"\n    },\n    {\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"type\": \"image/PNG\",\n      \"filename\": \"imageexample.png\",\n      \"disposition\": \"inline\",\n      \"contentId\": \"image-a\"\n    }\n  ]\n}"))
    .setHeader("Content-Type", "application/json")
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Request
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("http://{hostname}/v3/campaigns/transactional/send.json?apikey="))
    .POST(BodyPublishers.ofString("{ \n    \"From\": { \n        \"Email\": \"orders@example.com\", \n        \"Name\": \"Example Order Confirmation\" \n    }, \n    \"ReplyTo\": { \n        \"Email\": \"customer_service@example.com\", \n        \"Name\": \"Example Customer Service Team\" \n    }, \n    \"Subject\": \"Your Example Order Confirmation\", \n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \n    \"TemplateName\": \"My Sending Template\", \n    \"Content\": [ \n        { \n            \"Type\": \"text/html\", \n            \"Value\": \"<p>Hello world</p>\", \n            \"WebLocation\": \"https://mycompany.com/template.html\" \n        } \n    ], \n    \"Personalizations\": [ \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"john_doe@example.com\", \n                    \"Name\": \"John Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        }, \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"julia_doe@example.com\", \n                    \"Name\": \"Julia Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        } \n    ], \n    \"MailSettings\": { \n        \"BypassUnsubscribeManagement\": { \n            \"Enable\": true \n        } \n    },\n  \"attachments\": [\n    {\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"Type\": \"application/pdf\",\n      \"FileName\": \"attachementexample.pdf\",\n      \"disposition\": \"attachment\",\n      \"ContentId\": \"attachment-a\"\n    },\n    {\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"type\": \"image/PNG\",\n      \"filename\": \"imageexample.png\",\n      \"disposition\": \"inline\",\n      \"contentId\": \"image-a\"\n    }\n  ]\n}"))
    .setHeader("Content-Type", "application/json")
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Request
var settings = {
  "url": "{hostname}/v3/campaigns/transactional/send.json?apikey=",
  "method": "POST",
  "timeout": 0,
  "headers": {
    "Content-Type": "application/json"
  },
  "data": JSON.stringify({
    "From": {
      "Email": "orders@example.com",
      "Name": "Example Order Confirmation"
    },
    "ReplyTo": {
      "Email": "customer_service@example.com",
      "Name": "Example Customer Service Team"
    },
    "Subject": "Your Example Order Confirmation",
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
    "TemplateName": "My Sending Template",
    "Content": [
      {
        "Type": "text/html",
        "Value": "<p>Hello world</p>",
        "WebLocation": "https://mycompany.com/template.html"
      }
    ],
    "Personalizations": [
      {
        "To": [
          {
            "Email": "john_doe@example.com",
            "Name": "John Doe"
          }
        ],
        "Substitutions": {
          "key1": "value1",
          "key2": "value2"
        }
      },
      {
        "To": [
          {
            "Email": "julia_doe@example.com",
            "Name": "Julia Doe"
          }
        ],
        "Substitutions": {
          "key1": "value1",
          "key2": "value2"
        }
      }
    ],
    "MailSettings": {
      "BypassUnsubscribeManagement": {
        "Enable": true
      }
    },
    "attachments": [
      {
        "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
        "Type": "application/pdf",
        "FileName": "attachementexample.pdf",
        "disposition": "attachment",
        "ContentId": "attachment-a"
      },
      {
        "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
        "type": "image/PNG",
        "filename": "imageexample.png",
        "disposition": "inline",
        "contentId": "image-a"
      }
    ]
  }),
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
Request
var settings = {
  "url": "{hostname}/v3/campaigns/transactional/send.json?apikey=",
  "method": "POST",
  "timeout": 0,
  "headers": {
    "Content-Type": "application/json"
  },
  "data": JSON.stringify({
    "From": {
      "Email": "orders@example.com",
      "Name": "Example Order Confirmation"
    },
    "ReplyTo": {
      "Email": "customer_service@example.com",
      "Name": "Example Customer Service Team"
    },
    "Subject": "Your Example Order Confirmation",
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
    "TemplateName": "My Sending Template",
    "Content": [
      {
        "Type": "text/html",
        "Value": "<p>Hello world</p>",
        "WebLocation": "https://mycompany.com/template.html"
      }
    ],
    "Personalizations": [
      {
        "To": [
          {
            "Email": "john_doe@example.com",
            "Name": "John Doe"
          }
        ],
        "Substitutions": {
          "key1": "value1",
          "key2": "value2"
        }
      },
      {
        "To": [
          {
            "Email": "julia_doe@example.com",
            "Name": "Julia Doe"
          }
        ],
        "Substitutions": {
          "key1": "value1",
          "key2": "value2"
        }
      }
    ],
    "MailSettings": {
      "BypassUnsubscribeManagement": {
        "Enable": true
      }
    },
    "attachments": [
      {
        "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
        "Type": "application/pdf",
        "FileName": "attachementexample.pdf",
        "disposition": "attachment",
        "ContentId": "attachment-a"
      },
      {
        "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
        "type": "image/PNG",
        "filename": "imageexample.png",
        "disposition": "inline",
        "contentId": "image-a"
      }
    ]
  }),
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
Request
var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'POST',
  'hostname': '{hostname}',
  'path': '/v3/campaigns/transactional/send.json?apikey=',
  'headers': {
    'Content-Type': 'application/json'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = JSON.stringify({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": true
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
});

req.write(postData);

req.end();
Request
var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'POST',
  'hostname': '{hostname}',
  'path': '/v3/campaigns/transactional/send.json?apikey=',
  'headers': {
    'Content-Type': 'application/json'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = JSON.stringify({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": true
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
});

req.write(postData);

req.end();
Request
use LWP::UserAgent;

$ua = LWP::UserAgent->new();
$response = $ua->post(
    'http://{hostname}/v3/campaigns/transactional/send.json?apikey=',
    'Content-Type' => 'application/json',
    Content => "{ \n    \"From\": { \n        \"Email\": \"orders\@example.com\", \n        \"Name\": \"Example Order Confirmation\" \n    }, \n    \"ReplyTo\": { \n        \"Email\": \"customer_service\@example.com\", \n        \"Name\": \"Example Customer Service Team\" \n    }, \n    \"Subject\": \"Your Example Order Confirmation\", \n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \n    \"TemplateName\": \"My Sending Template\", \n    \"Content\": [ \n        { \n            \"Type\": \"text/html\", \n            \"Value\": \"<p>Hello world</p>\", \n            \"WebLocation\": \"https://mycompany.com/template.html\" \n        } \n    ], \n    \"Personalizations\": [ \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"john_doe\@example.com\", \n                    \"Name\": \"John Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        }, \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"julia_doe\@example.com\", \n                    \"Name\": \"Julia Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        } \n    ], \n    \"MailSettings\": { \n        \"BypassUnsubscribeManagement\": { \n            \"Enable\": true \n        } \n    },\n  \"attachments\": [\n    {\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"Type\": \"application/pdf\",\n      \"FileName\": \"attachementexample.pdf\",\n      \"disposition\": \"attachment\",\n      \"ContentId\": \"attachment-a\"\n    },\n    {\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"type\": \"image/PNG\",\n      \"filename\": \"imageexample.png\",\n      \"disposition\": \"inline\",\n      \"contentId\": \"image-a\"\n    }\n  ]\n}"
);
Request
use LWP::UserAgent;

$ua = LWP::UserAgent->new();
$response = $ua->post(
    'http://{hostname}/v3/campaigns/transactional/send.json?apikey=',
    'Content-Type' => 'application/json',
    Content => "{ \n    \"From\": { \n        \"Email\": \"orders\@example.com\", \n        \"Name\": \"Example Order Confirmation\" \n    }, \n    \"ReplyTo\": { \n        \"Email\": \"customer_service\@example.com\", \n        \"Name\": \"Example Customer Service Team\" \n    }, \n    \"Subject\": \"Your Example Order Confirmation\", \n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \n    \"TemplateName\": \"My Sending Template\", \n    \"Content\": [ \n        { \n            \"Type\": \"text/html\", \n            \"Value\": \"<p>Hello world</p>\", \n            \"WebLocation\": \"https://mycompany.com/template.html\" \n        } \n    ], \n    \"Personalizations\": [ \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"john_doe\@example.com\", \n                    \"Name\": \"John Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        }, \n        { \n            \"To\": [ \n                { \n                    \"Email\": \"julia_doe\@example.com\", \n                    \"Name\": \"Julia Doe\" \n                } \n            ], \n            \"Substitutions\": { \n                    \"key1\": \"value1\", \n                    \"key2\": \"value2\" \n                } \n        } \n    ], \n    \"MailSettings\": { \n        \"BypassUnsubscribeManagement\": { \n            \"Enable\": true \n        } \n    },\n  \"attachments\": [\n    {\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"Type\": \"application/pdf\",\n      \"FileName\": \"attachementexample.pdf\",\n      \"disposition\": \"attachment\",\n      \"ContentId\": \"attachment-a\"\n    },\n    {\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\n      \"type\": \"image/PNG\",\n      \"filename\": \"imageexample.png\",\n      \"disposition\": \"inline\",\n      \"contentId\": \"image-a\"\n    }\n  ]\n}"
);
Request
import http.client
import json

conn = http.client.HTTPSConnection("{hostname}")
payload = json.dumps({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": True
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
})
headers = {
  'Content-Type': 'application/json'
}
conn.request("POST", "/v3/campaigns/transactional/send.json?apikey=", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Request
import http.client
import json

conn = http.client.HTTPSConnection("{hostname}")
payload = json.dumps({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": True
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
})
headers = {
  'Content-Type': 'application/json'
}
conn.request("POST", "/v3/campaigns/transactional/send.json?apikey=", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Request
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => '{hostname}/v3/campaigns/transactional/send.json?apikey=',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Request
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => '{hostname}/v3/campaigns/transactional/send.json?apikey=',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{ 
    "From": { 
        "Email": "orders@example.com", 
        "Name": "Example Order Confirmation" 
    }, 
    "ReplyTo": { 
        "Email": "customer_service@example.com", 
        "Name": "Example Customer Service Team" 
    }, 
    "Subject": "Your Example Order Confirmation", 
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", 
    "TemplateName": "My Sending Template", 
    "Content": [ 
        { 
            "Type": "text/html", 
            "Value": "<p>Hello world</p>", 
            "WebLocation": "https://mycompany.com/template.html" 
        } 
    ], 
    "Personalizations": [ 
        { 
            "To": [ 
                { 
                    "Email": "john_doe@example.com", 
                    "Name": "John Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        }, 
        { 
            "To": [ 
                { 
                    "Email": "julia_doe@example.com", 
                    "Name": "Julia Doe" 
                } 
            ], 
            "Substitutions": { 
                    "key1": "value1", 
                    "key2": "value2" 
                } 
        } 
    ], 
    "MailSettings": { 
        "BypassUnsubscribeManagement": { 
            "Enable": true 
        } 
    },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Request
require "uri"
require "json"
require "net/http"

url = URI("{hostname}/v3/campaigns/transactional/send.json?apikey=")

http = Net::HTTP.new(url.host, url.port);
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request.body = JSON.dump({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": true
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
})

response = http.request(request)
puts response.read_body

Request
require "uri"
require "json"
require "net/http"

url = URI("{hostname}/v3/campaigns/transactional/send.json?apikey=")

http = Net::HTTP.new(url.host, url.port);
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request.body = JSON.dump({
  "From": {
    "Email": "orders@example.com",
    "Name": "Example Order Confirmation"
  },
  "ReplyTo": {
    "Email": "customer_service@example.com",
    "Name": "Example Customer Service Team"
  },
  "Subject": "Your Example Order Confirmation",
  "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8",
  "TemplateName": "My Sending Template",
  "Content": [
    {
      "Type": "text/html",
      "Value": "<p>Hello world</p>",
      "WebLocation": "https://mycompany.com/template.html"
    }
  ],
  "Personalizations": [
    {
      "To": [
        {
          "Email": "john_doe@example.com",
          "Name": "John Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "To": [
        {
          "Email": "julia_doe@example.com",
          "Name": "Julia Doe"
        }
      ],
      "Substitutions": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ],
  "MailSettings": {
    "BypassUnsubscribeManagement": {
      "Enable": true
    }
  },
  "attachments": [
    {
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "Type": "application/pdf",
      "FileName": "attachementexample.pdf",
      "disposition": "attachment",
      "ContentId": "attachment-a"
    },
    {
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",
      "type": "image/PNG",
      "filename": "imageexample.png",
      "disposition": "inline",
      "contentId": "image-a"
    }
  ]
})

response = http.request(request)
puts response.read_body

Request
 package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "{hostname}/v3/campaigns/transactional/send.json?apikey="
  method := "POST"

  payload := strings.NewReader(`{ `+"
"+`
    "From": { `+"
"+`
        "Email": "orders@example.com", `+"
"+`
        "Name": "Example Order Confirmation" `+"
"+`
    }, `+"
"+`
    "ReplyTo": { `+"
"+`
        "Email": "customer_service@example.com", `+"
"+`
        "Name": "Example Customer Service Team" `+"
"+`
    }, `+"
"+`
    "Subject": "Your Example Order Confirmation", `+"
"+`
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", `+"
"+`
    "TemplateName": "My Sending Template", `+"
"+`
    "Content": [ `+"
"+`
        { `+"
"+`
            "Type": "text/html", `+"
"+`
            "Value": "<p>Hello world</p>", `+"
"+`
            "WebLocation": "https://mycompany.com/template.html" `+"
"+`
        } `+"
"+`
    ], `+"
"+`
    "Personalizations": [ `+"
"+`
        { `+"
"+`
            "To": [ `+"
"+`
                { `+"
"+`
                    "Email": "john_doe@example.com", `+"
"+`
                    "Name": "John Doe" `+"
"+`
                } `+"
"+`
            ], `+"
"+`
            "Substitutions": { `+"
"+`
                    "key1": "value1", `+"
"+`
                    "key2": "value2" `+"
"+`
                } `+"
"+`
        }, `+"
"+`
        { `+"
"+`
            "To": [ `+"
"+`
                { `+"
"+`
                    "Email": "julia_doe@example.com", `+"
"+`
                    "Name": "Julia Doe" `+"
"+`
                } `+"
"+`
            ], `+"
"+`
            "Substitutions": { `+"
"+`
                    "key1": "value1", `+"
"+`
                    "key2": "value2" `+"
"+`
                } `+"
"+`
        } `+"
"+`
    ], `+"
"+`
    "MailSettings": { `+"
"+`
        "BypassUnsubscribeManagement": { `+"
"+`
            "Enable": true `+"
"+`
        } `+"
"+`
    },`+"
"+`
  "attachments": [`+"
"+`
    {`+"
"+`
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",`+"
"+`
      "Type": "application/pdf",`+"
"+`
      "FileName": "attachementexample.pdf",`+"
"+`
      "disposition": "attachment",`+"
"+`
      "ContentId": "attachment-a"`+"
"+`
    },`+"
"+`
    {`+"
"+`
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",`+"
"+`
      "type": "image/PNG",`+"
"+`
      "filename": "imageexample.png",`+"
"+`
      "disposition": "inline",`+"
"+`
      "contentId": "image-a"`+"
"+`
    }`+"
"+`
  ]`+"
"+`
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
Request
 package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "{hostname}/v3/campaigns/transactional/send.json?apikey="
  method := "POST"

  payload := strings.NewReader(`{ `+"
"+`
    "From": { `+"
"+`
        "Email": "orders@example.com", `+"
"+`
        "Name": "Example Order Confirmation" `+"
"+`
    }, `+"
"+`
    "ReplyTo": { `+"
"+`
        "Email": "customer_service@example.com", `+"
"+`
        "Name": "Example Customer Service Team" `+"
"+`
    }, `+"
"+`
    "Subject": "Your Example Order Confirmation", `+"
"+`
    "TemplateId": "d59b39d5-da76-4797-8f24-c1265bb903b8", `+"
"+`
    "TemplateName": "My Sending Template", `+"
"+`
    "Content": [ `+"
"+`
        { `+"
"+`
            "Type": "text/html", `+"
"+`
            "Value": "<p>Hello world</p>", `+"
"+`
            "WebLocation": "https://mycompany.com/template.html" `+"
"+`
        } `+"
"+`
    ], `+"
"+`
    "Personalizations": [ `+"
"+`
        { `+"
"+`
            "To": [ `+"
"+`
                { `+"
"+`
                    "Email": "john_doe@example.com", `+"
"+`
                    "Name": "John Doe" `+"
"+`
                } `+"
"+`
            ], `+"
"+`
            "Substitutions": { `+"
"+`
                    "key1": "value1", `+"
"+`
                    "key2": "value2" `+"
"+`
                } `+"
"+`
        }, `+"
"+`
        { `+"
"+`
            "To": [ `+"
"+`
                { `+"
"+`
                    "Email": "julia_doe@example.com", `+"
"+`
                    "Name": "Julia Doe" `+"
"+`
                } `+"
"+`
            ], `+"
"+`
            "Substitutions": { `+"
"+`
                    "key1": "value1", `+"
"+`
                    "key2": "value2" `+"
"+`
                } `+"
"+`
        } `+"
"+`
    ], `+"
"+`
    "MailSettings": { `+"
"+`
        "BypassUnsubscribeManagement": { `+"
"+`
            "Enable": true `+"
"+`
        } `+"
"+`
    },`+"
"+`
  "attachments": [`+"
"+`
    {`+"
"+`
      "content": "iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",`+"
"+`
      "Type": "application/pdf",`+"
"+`
      "FileName": "attachementexample.pdf",`+"
"+`
      "disposition": "attachment",`+"
"+`
      "ContentId": "attachment-a"`+"
"+`
    },`+"
"+`
    {`+"
"+`
      "content": "iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==",`+"
"+`
      "type": "image/PNG",`+"
"+`
      "filename": "imageexample.png",`+"
"+`
      "disposition": "inline",`+"
"+`
      "contentId": "image-a"`+"
"+`
    }`+"
"+`
  ]`+"
"+`
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
Request
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "{hostname}/v3/campaigns/transactional/send.json?apikey=");
var content = new StringContent("{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
Request
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "{hostname}/v3/campaigns/transactional/send.json?apikey=");
var content = new StringContent("{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
Request
#import <Foundation/Foundation.h>

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"%7Bhostname%7D/v3/campaigns/transactional/send.json?apikey="]
  cachePolicy:NSURLRequestUseProtocolCachePolicy
  timeoutInterval:10.0];
NSDictionary *headers = @{
  @"Content-Type": @"application/json"
};

[request setAllHTTPHeaderFields:headers];
NSData *postData = [[NSData alloc] initWithData:[@"{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];

[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  if (error) {
    NSLog(@"%@", error);
    dispatch_semaphore_signal(sema);
  } else {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSError *parseError = nil;
    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    NSLog(@"%@",responseDictionary);
    dispatch_semaphore_signal(sema);
  }
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
Request
#import <Foundation/Foundation.h>

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"%7Bhostname%7D/v3/campaigns/transactional/send.json?apikey="]
  cachePolicy:NSURLRequestUseProtocolCachePolicy
  timeoutInterval:10.0];
NSDictionary *headers = @{
  @"Content-Type": @"application/json"
};

[request setAllHTTPHeaderFields:headers];
NSData *postData = [[NSData alloc] initWithData:[@"{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];

[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  if (error) {
    NSLog(@"%@", error);
    dispatch_semaphore_signal(sema);
  } else {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSError *parseError = nil;
    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    NSLog(@"%@",responseDictionary);
    dispatch_semaphore_signal(sema);
  }
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
Request
let parameters = "{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}"
let postData = parameters.data(using: .utf8)

var request = URLRequest(url: URL(string: "{hostname}/v3/campaigns/transactional/send.json?apikey=")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
  guard let data = data else {
    print(String(describing: error))
    return
  }
  print(String(data: data, encoding: .utf8)!)
}

task.resume()
Request
let parameters = "{ \r\n    \"From\": { \r\n        \"Email\": \"orders@example.com\", \r\n        \"Name\": \"Example Order Confirmation\" \r\n    }, \r\n    \"ReplyTo\": { \r\n        \"Email\": \"customer_service@example.com\", \r\n        \"Name\": \"Example Customer Service Team\" \r\n    }, \r\n    \"Subject\": \"Your Example Order Confirmation\", \r\n    \"TemplateId\": \"d59b39d5-da76-4797-8f24-c1265bb903b8\", \r\n    \"TemplateName\": \"My Sending Template\", \r\n    \"Content\": [ \r\n        { \r\n            \"Type\": \"text/html\", \r\n            \"Value\": \"<p>Hello world</p>\", \r\n            \"WebLocation\": \"https://mycompany.com/template.html\" \r\n        } \r\n    ], \r\n    \"Personalizations\": [ \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"john_doe@example.com\", \r\n                    \"Name\": \"John Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        }, \r\n        { \r\n            \"To\": [ \r\n                { \r\n                    \"Email\": \"julia_doe@example.com\", \r\n                    \"Name\": \"Julia Doe\" \r\n                } \r\n            ], \r\n            \"Substitutions\": { \r\n                    \"key1\": \"value1\", \r\n                    \"key2\": \"value2\" \r\n                } \r\n        } \r\n    ], \r\n    \"MailSettings\": { \r\n        \"BypassUnsubscribeManagement\": { \r\n            \"Enable\": true \r\n        } \r\n    },\r\n  \"attachments\": [\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAANSUhEUgAABYMAAAOgCAYAAABvGmkhAAAABGdBTUEAAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"Type\": \"application/pdf\",\r\n      \"FileName\": \"attachementexample.pdf\",\r\n      \"disposition\": \"attachment\",\r\n      \"ContentId\": \"attachment-a\"\r\n    },\r\n    {\r\n      \"content\": \"iVBORw0KGgoAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAfcAYDAAAAADQB4zBAAAAAAB9wBgMAAAAANAHjMEAAAAAAH3AGAwAAAAA0AeMwQAAAAAAPe+T+J/nnNIPnRqhbwAAAABJRU5ErkJggg==\",\r\n      \"type\": \"image/PNG\",\r\n      \"filename\": \"imageexample.png\",\r\n      \"disposition\": \"inline\",\r\n      \"contentId\": \"image-a\"\r\n    }\r\n  ]\r\n}"
let postData = parameters.data(using: .utf8)

var request = URLRequest(url: URL(string: "{hostname}/v3/campaigns/transactional/send.json?apikey=")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
  guard let data = data else {
    print(String(describing: error))
    return
  }
  print(String(data: data, encoding: .utf8)!)
}

task.resume()
Response
json
{
  "TotalAccepted": 1,
  "TotalExcluded": 1,
  "ExcludedRecipients": [
    {
      "Email": "recipient@domain.dom",
      "Reason": "The recipient was found with status bounced"
    }
  ]
}

Clone an existing campaign

Abstract

Describes the request and response details of this Moosend API endpoint to clone a campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you want to clone.

Format

path

string

true

The supported file format for getting a response.

Possible values: jsonand xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the cloned campaign:

  • ID - the ID of the cloned campaign.

  • Name - the name of the campaign.

  • Subject- the subject of the campaign.

  • WebLocation - the web location of the HTML campaign.

  • HTMLContent - the HTML content of the campaign.

  • PlainContent - the content of the campaign in plain text.

  • Sender - a list that contains the following information about the campaign sender:

    • ID - the ID of the sender.

    • Name - the name of the sender.

    • Email - the email address of the sender.

    • CreatedOn - the date that the sender was created.

    • IsEnabled - this is true if the sender is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the sender is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the sender is enabled and false if it is not.

    • DkimPublic - specifies the sender's email public DKIM.

  • DeliveredOn - the date-time the campaign was delivered. This is null for a cloned campaign.

  • ReplyToEmail - an object that contains details about the Reply to email address selected to receive replies from the campaign:

    • ID - the ID of the Reply to email receiver.

    • Name - the name of the Reply to email receiver.

    • Email - the email address of the Reply to email receiver.

    • CreatedOn - the date that the Reply to email receiver was created.

    • IsEnabled - this is true if the Reply to email receiver is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the Reply to email receiver is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the Reply to email receiver is enabled and false if it is not.

    • DkimPublic - specifies the Reply to email receiver's email public DKIM.

  • CreatedOn - the date-time the campaign was created.

  • UpdatedOn - the date-time that the campaign was updated.

  • ScheduledFor - the date-time the campaign is scheduled to be delivered. This is null for a cloned campaign.

  • TimeZone - the selected time zone for the account.

  • FormatType - the format type of the campaign. This is 0 for HTML, 1 for Template, and 2 for Plain Text.

  • ABCampaignData : This is null if the cloned campaign is a regular campaign. If the cloned campaign is an A/B split campaign, the object contains the following information:

    • ID - the four-digit integer ID of the ABCampaignData.

    • SubjectB - if the A/B split campaign is testing the subject, this is the subject line for campaign B.

    • PlainContentB - if the A/B split campaign is testing the content, this is the plain text content for campaign B.

    • HTMLContentB - if the A/B split campaign is testing the content, this is the HTML content for campaign B.

    • WebLocationB - if the A/B split campaign is testing the content, this is the web location for campaign B.

    • SenderB - if the A/B split campaign is testing the sender, this is campaign B's sender.

    • HoursToTest - the total number of hours to test campaigns A and B of your split test before sending the winning version.

    • ListPercentage - specifies the size of your test group in your list.

    • ABCampaignType - specifies the type of A/B split campaign. This is 0 for sender, 1 for content, and 2 for subject line

    • ABWinnerSelectionType - specifies the type of test that defines the winning version of the campaign. This is 0 for a unique opens test and 1 for a unique clicks test.

    • DeliveredOnA - the date-time campaign A was delivered. This is null for a cloned campaign.

    • DeliveredOnB - the date-time campaign B was delivered. This is null for a cloned campaign.

  • MailingLists - a list that contains the email lists or segments that that campaign is sent to.

    • MailingListID - the ID of the email list.

    • SegmentID - the ID of the selected segment. This is 0 if there is no segment selected.

  • ConfirmationTo - the email address to which a confirmation message is sent when the campaign has been successfully sent.

  • Status - status of the campaign. The cloned campaign has 0 for status.

  • IsTransactional - specifies whether the campaign was created using SMTP. This can be true or false.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=
Request
curl --include \
     --request POST \
'https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity<String> payload = Entity.text("");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

    using (var content = new StringContent(""))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/clone.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def jsonObj = new JsonSlurper().parseText()
response = client.post( path : "/campaigns/{CampaignID}/clone.{Format}{?apikey}",
                        body : jsonObj,
                        
                        contentType : ANY )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "248f97f5-1e5f-4e17-8fa8-818dc112be10",
    "Name": "Test",
    "Subject": "Test",
    "WebLocation": "http://www.your-domain.com/newsletter",
    "HTMLContent": "Some html content",
    "PlainContent": "Plain context ... ",
    "Sender": {
      "ID": "e9d2ed56-fc20-4337-bb6a-8b5884e8dfa6",
      "Name": "Test",
      "Email": "test@email.com",
      "CreatedOn": "/Date(1457526079160+0100)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": true,
      "DkimPublic": "sender email dkim public"
    },
    "DeliveredOn": null,
    "ReplyToEmail": {
      "ID": "21234a-cede-1234-1234-1bd8d7a46d2d",
      "Name": "Andreas",
      "Email": "andreas@email.com",
      "CreatedOn": "/Date(1457526079160+0100)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": true,
      "DkimPublic": "reply to email dkim public"
    },
    "CreatedOn": "/Date(1469541491211)/",
    "UpdatedOn": "/Date(1469541491211)/",
    "ScheduledFor": null,
    "Timezone": "Korea Standard Time",
    "FormatType": 0,
    "ABCampaignData": {
      "ID": 4080,
      "SubjectB": "B Subject",
      "PlainContentB": null,
      "HTMLContentB": null,
      "WebLocationB": null,
      "SenderB": null,
      "HoursToTest": 3,
      "ListPercentage": 19,
      "ABCampaignType": 2,
      "ABWinnerSelectionType": 1,
      "DeliveredOnA": null,
      "DeliveredOnB": null
    },
    "MailingLists": [
      {
        "MailingListID": "e9d2ed56-fc20-4337-bb6a-8b5884e8dfa6",
        "SegmentID": 0
      }
    ],
    "ConfirmationTo": "test@email.com",
    "Status": 0,
    "IsTransactional": false
  }
}

Delete a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to delete a campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the draft or sent campaign that you want to delete.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
DELETE https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=
Request
curl --include \
     --request DELETE \
'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .delete();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('DELETE', 'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'DELETE',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->delete("https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=')
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.delete 'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("DELETE", "https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.DeleteAsync("campaigns/{CampaignID}/clone.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "DELETE"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.delete( path : "/campaigns/{CampaignID}/clone.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"DELETE"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "DELETE"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Update a draft campaign

Abstract

Describes the request and response details of this Moosend API endpoint to update a draft campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

CampaignID

path

string

true

The ID of the campaign that you want to update.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the campaign.

Subject

body

string

false

The subject line of the campaign.

SenderEmail

body

string

false

The email address of the campaign sender.

ReplyToEmail

body

string

false

The email address selected to receive replies from the campaign. This must be one of your campaign senders. If not specified, the SenderEmail is assumed.

ConfirmationToEmail

body

string

false

The email address used to send a confirmation message when the campaign has been successfully sent. This can be any valid email address. If not specified, the SenderEmail is assumed.

WebLocation

body

string

false

The URL used to retrieve the HTML content of the campaign. Moosend automatically moves all CSS inline.

MailingLists

body

array

false

A list of email lists in your account that is used to send the campaign.

SegmentID

body

string

false

The ID of a segment in the selected email list. If not specified, the campaign is sent to all active subscribers of the email list.

IsAB

body

Boolean

false

A flag that defines if a campaign is an A/B split campaign. If true, you must fill out A/B split campaign parameters.

TrackInGoogleAnalytics

body

Boolean

false

Specifies if tracking is enabled for the campaign. You must have Google Analytics configured on your site to use this feature.

A/B split campaign parameters

Use these parameters when updating an A/B split campaign. If you specify any of the parameters below when updating a regular campaign, they are ignored in the request.

Name

In

Type

Required

Description

ABCampaignType

body

string

true

Specify the type of test to be performed in the AB split campaign to determine the winning version:

  • Subjectline - test two different versions of the subject line.

  • Content - test two different versions of the campaign content.

  • Sender - test two different versions of the campaign sender.

SubjectB

body

string

false

If testing A/B split campaigns with two subject line versions, this is the second subject version of the subject.

WebLocationB

body

string

false

If testing A/B split campaigns with two HTML content versions, this is the web location of the second HTML content version.

SenderEmailB

body

string

false

If testing A/B split campaigns with two sender versions, this is the email address of the second campaign sender. This must be one of the senders defined in your account.

HoursToTest

body

integer

false

Specify how long the test runs, before determining the winning campaign version to be sent to the rest of the recipients.

This must be an integer between 1 and 24.

ListPercentage

body

integer

false

Specifies a portion of the target recipients to get the test campaign versions. For example, if you specify 10, then 10% of your recipients receive campaign A and another 10% receive the campaign B version.

This must be an integer between 5 and 40.

ABWinnerSelectionType

body

string

false

Specifies the method to determine the winning version for the test. If not set, OpenRate is assumed.

  • OpenRate -determine the winner based on the version that achieved more opens.

  • TotalUniqueClicks - determine the winner based on the version that achieved more unique link clicks.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=

Request body:
{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "WebLocation": "http://www.mysite.gr/newsletter/index",
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"Test campaign\",
    \"Subject\":\"Some subject\",
    \"SenderEmail\":\"something@email.com\",
    \"ReplyToEmail\":\"something@email.com\",
    \"ConfirmationToEmail\":\"something@email.com\",
    \"WebLocation\":\"http://www.mysite.gr/newsletter/index\",
    \"MailingLists\": [
        {
            \"MailingListID\":\"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
            \"SegmentID\":\"10166\"
        },
        {
            \"MailingListID\":\"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
        }
    ],
    \"IsAB\":\"true\",
    \"ABCampaignType\":\"Content\",
    \"WebLocationB\":\"http://www.mysite.gr/newsletter/index\",
    \"HoursToTest\":\"2\",
    \"ListPercentage\":\"20\",
    \"ABWinnerSelectionType\":\"OpenRate\"
}" \
'https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Test campaign',
  'Subject': 'Some subject',
  'SenderEmail': 'something@email.com',
  'ReplyToEmail': 'something@email.com',
  'ConfirmationToEmail': 'something@email.com',
  'WebLocation': 'http://www.mysite.gr/newsletter/index',
  'MailingLists': [
    {
      'MailingListID': 'adaf2fe1-55db-42dc-aaf8-56d8f502138d',
      'SegmentID': '10166'
    },
    {
      'MailingListID': 'dce99b7a-2619-4805-aaeb-7fecdcb3c71b'
    }
  ],
  'IsAB': 'true',
  'ABCampaignType': 'Content',
  'WebLocationB': 'http://www.mysite.gr/newsletter/index',
  'HoursToTest': '2',
  'ListPercentage': '20',
  'ABWinnerSelectionType': 'OpenRate'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Test campaign",  "Subject": "Some subject",  "SenderEmail": "something@email.com",  "ReplyToEmail": "something@email.com",  "ConfirmationToEmail": "something@email.com",  "WebLocation": "http://www.mysite.gr/newsletter/index",  "MailingLists": [    {      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",      "SegmentID": "10166"    },    {      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"    }  ],  "IsAB": "true",  "ABCampaignType": "Content",  "WebLocationB": "http://www.mysite.gr/newsletter/index",  "HoursToTest": "2",  "ListPercentage": "20",  "ABWinnerSelectionType": "OpenRate"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Test campaign",
    "Subject": "Some subject",
    "SenderEmail": "something@email.com",
    "ReplyToEmail": "something@email.com",
    "ConfirmationToEmail": "something@email.com",
    "WebLocation": "http://www.mysite.gr/newsletter/index",
    "MailingLists": [
      {
        "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
        "SegmentID": "10166"
      },
      {
        "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
      }
    ],
    "IsAB": "true",
    "ABCampaignType": "Content",
    "WebLocationB": "http://www.mysite.gr/newsletter/index",
    "HoursToTest": "2",
    "ListPercentage": "20",
    "ABWinnerSelectionType": "OpenRate"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Test campaign\",
  \"Subject\": \"Some subject\",
  \"SenderEmail\": \"something@email.com\",
  \"ReplyToEmail\": \"something@email.com\",
  \"ConfirmationToEmail\": \"something@email.com\",
  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",
  \"MailingLists\": [
    {
      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
      \"SegmentID\": \"10166\"
    },
    {
      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
    }
  ],
  \"IsAB\": \"true\",
  \"ABCampaignType\": \"Content\",
  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",
  \"HoursToTest\": \"2\",
  \"ListPercentage\": \"20\",
  \"ABWinnerSelectionType\": \"OpenRate\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "WebLocation": "http://www.mysite.gr/newsletter/index",
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/clone.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Test campaign\"",
  \""Subject\"": \""Some subject\"",
  \""SenderEmail\"": \""something@email.com\"",
  \""ReplyToEmail\"": \""something@email.com\"",
  \""ConfirmationToEmail\"": \""something@email.com\"",
  \""WebLocation\"": \""http://www.mysite.gr/newsletter/index\"",
  \""MailingLists\"": [
    {
      \""MailingListID\"": \""adaf2fe1-55db-42dc-aaf8-56d8f502138d\"",
      \""SegmentID\"": \""10166\""
    },
    {
      \""MailingListID\"": \""dce99b7a-2619-4805-aaeb-7fecdcb3c71b\""
    }
  ],
  \""IsAB\"": \""true\"",
  \""ABCampaignType\"": \""Content\"",
  \""WebLocationB\"": \""http://www.mysite.gr/newsletter/index\"",
  \""HoursToTest\"": \""2\"",
  \""ListPercentage\"": \""20\"",
  \""ABWinnerSelectionType\"": \""OpenRate\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "WebLocation": "http://www.mysite.gr/newsletter/index",
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}')
response = client.post( path : "/campaigns/{CampaignID}/clone.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Test a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to test a draft campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

CampaignID

path

string

true

The ID of the draft campaign that you want to test.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

TestEmails

body

array

true

A list of email addresses that you want to use to send your test campaign. Use a comma (,) to separate up to a maximum of five email addresses.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=

Request body:
{
  "TestEmails": [
    "email1@email.com",
    "email2@email.com"
  ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"TestEmails\":
    [
        \"email1@email.com\",
        \"email2@email.com\"
    ]
}" \
'https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"TestEmails\": [    \"email1@email.com\",    \"email2@email.com\"  ]}");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'TestEmails': [
    'email1@email.com',
    'email2@email.com'
  ]
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"TestEmails\": [    \"email1@email.com\",    \"email2@email.com\"  ]}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "TestEmails": [    "email1@email.com",    "email2@email.com"  ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "TestEmails": [
      "email1@email.com",
      "email2@email.com"
    ]
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"TestEmails\": [
    \"email1@email.com\",
    \"email2@email.com\"
  ]
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "TestEmails": [
    "email1@email.com",
    "email2@email.com"
  ]
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"TestEmails\": [\n    \"email1@email.com\",\n    \"email2@email.com\"\n  ]\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"TestEmails\": [    \"email1@email.com\",    \"email2@email.com\"  ]}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/send_test.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""TestEmails\"": [
    \""email1@email.com\"",
    \""email2@email.com\""
  ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "TestEmails": [
    "email1@email.com",
    "email2@email.com"
  ]
}')
response = client.post( path : "/campaigns/{CampaignID}/send_test.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"TestEmails\": [\n    \"email1@email.com\",\n    \"email2@email.com\"\n  ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"TestEmails\": [\n    \"email1@email.com\",\n    \"email2@email.com\"\n  ]\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Send a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to send a campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the draft campaign that you want to send.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=
Request
curl --include \
     --request POST \
'https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity<String> payload = Entity.text("");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

    using (var content = new StringContent(""))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/send.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def jsonObj = new JsonSlurper().parseText()
response = client.post( path : "/campaigns/{CampaignID}/send.{Format}{?apikey}",
                        body : jsonObj,
                        
                        contentType : ANY )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Schedule a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to schedule a campaign for delivery.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

CampaignID

path

string

true

The ID of the campaign that you want to schedule.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

DateTime

body

date

true

The specific date and time the campaign is scheduled to be delivered.

Use the same format that you have in the Time and date settings in your account. For example, dd-mm-yyyy.

Timezone

body

string

false

The time zone of your specified date and time.

If you don't specify any timezone value, the time zone in your time and date settings is used.

Timezone values

The available time zones are the following:

  • Dateline Standard Time

  • Samoa Standard Time

  • Hawaiian Standard Time

  • Alaskan Standard Time

  • Pacific Standard Time

  • Pacific Standard Time (Mexico)

  • US Mountain Standard Time

  • Mountain Standard Time

  • Central Standard Time

  • Central Standard Time (Mexico)

  • Canada Central Standard Time

  • SA Pacific Standard Time

  • US Eastern Standard Time

  • Eastern Standard Time

  • Venezuela Standard Time

  • Atlantic Standard Time

  • SA Western Standard Time

  • Central Brazilian Standard Time

  • Pacific SA Standard Time

  • Newfoundland Standard Time

  • E. South America Standard Time

  • Argentina Standard Time

  • SA Eastern Standard Time

  • Greenland Standard Time

  • Montevideo Standard Time

  • Mid-Atlantic Standard Time

  • Azores Standard Time

  • Cape Verde Standard Time

  • Greenwich Standard Time

  • GMT Standard Time

  • Morocco Standard Time

  • W. Central Africa Standard Time

  • Central European Standard Time

  • Romance Standard Time

  • W. Europe Standard Time

  • Namibia Standard Time

  • E. Europe Standard Time

  • Israel Standard Time

  • FLE Standard Time

  • South Africa Standard Time

  • Egypt Standard Time

  • Middle East Standard Time

  • GTB Standard Time

  • Jordan Standard Time

  • Iran Standard Time

  • Georgian Standard Time

  • E. Africa Standard Time

  • Russian Standard Time

  • Arab Standard Time

  • Arabic Standard Time

  • Caucasus Standard Time

  • Mauritius Standard Time

  • Azerbaijan Standard Time

  • Arabian Standard Time

  • Afghanistan Standard Time

  • West Asia Standard Time

  • Pakistan Standard Time

  • Ekaterinburg Standard Time

  • Sri Lanka Standard Time

  • India Standard Time

  • Nepal Standard Time

  • N. Central Asia Standard Time

  • Central Asia Standard Time

  • Myanmar Standard Time

  • North Asia Standard Time

  • SE Asia Standard Time

  • Taipei Standard Time

  • W. Australia Standard Time

  • Singapore Standard Time

  • North Asia East Standard Time

  • China Standard Time

  • Yakutsk Standard Time

  • Korea Standard Time

  • Tokyo Standard Time

  • AUS Central Standard Time

  • Cen. Australia Standard Time

  • AUS Eastern Standard Time

  • West Pacific Standard Time

  • Tasmania Standard Time

  • Vladivostok Standard Time

  • Central Pacific Standard Time

  • New Zealand Standard Time

  • Tonga Standard Time

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response message. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=

Request body:
{
  "DateTime": "24-06-2023 13:17",
  "Timezone": "US Eastern Standard Time"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"DateTime\":\"24-06-2023 13:17\",
    \"Timezone\":\"US Eastern Standard Time\"
}" \
'https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"DateTime\": \"24-06-2016 13:17\",  \"Timezone\": \"US Eastern Standard Time\"}");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'DateTime': '24-06-2023 13:17',
  'Timezone': 'US Eastern Standard Time'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"DateTime\": \"24-06-2023 13:17\",  \"Timezone\": \"US Eastern Standard Time\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "DateTime": "24-06-2023 13:17",  "Timezone": "US Eastern Standard Time"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "DateTime": "24-06-2023 13:17",
    "Timezone": "US Eastern Standard Time"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"DateTime\": \"24-06-2023 13:17\",
  \"Timezone\": \"US Eastern Standard Time\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "DateTime": "24-06-2023 13:17",
  "Timezone": "US Eastern Standard Time"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"DateTime\": \"24-06-2023 13:17\",\n  \"Timezone\": \"US Eastern Standard Time\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"DateTime\": \"24-06-2023 13:17\",  \"Timezone\": \"US Eastern Standard Time\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/schedule.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""DateTime\"": \""24-06-2023 13:17\"",
  \""Timezone\"": \""US Eastern Standard Time\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "DateTime": "24-06-2023 13:17",
  "Timezone": "US Eastern Standard Time"
}')
response = client.post( path : "/campaigns/{CampaignID}/schedule.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"DateTime\": \"24-06-2023 13:17\",\n  \"Timezone\": \"US Eastern Standard Time\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"DateTime\": \"24-06-2023 13:17\",\n  \"Timezone\": \"US Eastern Standard Time\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Unschedule a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to unschedule a campaign that is scheduled for delivery.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you want to unschedule.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response message. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=
Request
curl --include \
     --request POST \
'https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity<String> payload = Entity.text("");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

    using (var content = new StringContent(""))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/schedule.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def jsonObj = new JsonSlurper().parseText()
response = client.post( path : "/campaigns/{CampaignID}/schedule.{Format}{?apikey}",
                        body : jsonObj,
                        
                        contentType : ANY )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Get campaign statistics

Abstract

Describes the request and response details of this Moosend API endpoint to get campaign statistics.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you are fetching statistics for.

Type

path

string

false

The type of activity used to get information and display statistics. Possible values are:

  • Sent - when and to which recipients the campaign was sent.

  • Opened - who opened the campaign.

  • LinkClicked - who clicked on which links in the campaign.

  • Forward - who forwarded the campaign using the relevant link in the email body and when.

  • Unsubscribed - who unsubscribed from the campaign by clicking the unsubscribe link and when.

  • Bounced - which email recipients failed to receive the campaign. If not specified, Sent value is used by default.

  • Complained - which email recipients reported your campaign as spam through their email service.

  • Activity - all types of activities for the campaign.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

date

query

date

false

The specific year, month, and day the activity occurred. The date has a YYYY/MM/DD format.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and Analytics information for the campaign:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of results that are included in the response.

      • TotalPageCount - the total number of pages in your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • Analytics - a list of recipients containing the following information for each recipient:

      • Context - the email address of the recipient.

      • ContextName - the name of the recipient.

      • TotalCount - the total number of statistics based on the activity Type made by the recipient. This can be opens, link clicks, and so on.

      • UniqueCount - the total number of unique statistics based on the activity Type made by the recipient. This can be opens, link clicks, and so on.

      • ContextDescription : If the selected Type is Unsubscribed, this contains the date-time the recipient unsubscribed from the campaign.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 1,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Analytics": [
      {
        "Context": "recipient@email.com",
        "ContextName": "recipient name",
        "TotalCount": 1,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient2@email.com",
        "ContextName": "recipient2 name",
        "TotalCount": 1,
        "UniqueCount": 0,
        "ContextDescription": null
      }
    ]
  }
}

Get campaign statistics with paging and filter

Abstract

Describes the request and response details of this Moosend API endpoint to get campaign statistics with paging and filter information.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you are fetching statistics for.

Type

path

string

false

The type of activity used to get information and display statistics. Possible values are:

  • Sent - when and to which recipients the campaign was sent.

  • Opened - who opened the campaign.

  • LinkClicked - who clicked on which links in the campaign.

  • Forward - who forwarded the campaign using the relevant link in the email body and when.

  • Unsubscribed - who unsubscribed from the campaign by clicking the unsubscribe link and when.

  • Bounced - which email recipients failed to receive the campaign. If not specified, Sent value is used by default.

  • Complained - which email recipients reported your campaign as spam through their email service.

  • Activity - all types of activities for the campaign.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Page

query

number

false

The page number to display results for. If not specified, the first page is returned.

PageSize

query

number

false

The maximum number of results per page. This must be a positive integer up to 1000.

Returns 50 results per page if not specified. If a value greater than 1000 is specified, it is treated as 1000. 

From

query

date

false

The start date value to return results.  If not specified, results are returned from the date the campaign was sent. From date has a DD-MM-YYYY format.

To

query

date

false

The end date value to return results. If not specified, results are returned up to the current date.  To date has a DD-MM-YYYY format.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and Analytics information for the campaign:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of results that are included in the response.

      • TotalPageCount - the total number of pages in your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • Analytics - a list of recipients containing the following information for each recipient:

      • Context - the email address of the recipient.

      • ContextName - the name of the recipient.

      • TotalCount - the total number of statistics based on the activity Type made by the recipient. This can be opens, link clicks, and so on.

      • UniqueCount - the total number of unique statistics based on the activity Type made by the recipient. This can be opens, link clicks, and so on.

      • ContextDescription : If the selected Type is Unsubscribed, this contains the date-time the recipient unsubscribed from the campaign.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From&To=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 5,
      "CurrentPage": 1,
      "TotalResults": 374,
      "TotalPageCount": 75,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Analytics": [
      {
        "Context": "recipient1@email.com",
        "ContextName": "",
        "TotalCount": 1,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient2@email.com",
        "ContextName": "Paul",
        "TotalCount": 1,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient3@email.com",
        "ContextName": "John",
        "TotalCount": 5,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient4@email.com",
        "ContextName": "Marc",
        "TotalCount": 4,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient5@email.com",
        "ContextName": "",
        "TotalCount": 3,
        "UniqueCount": 0,
        "ContextDescription": null
      }
    ]
  }
}

Get campaign summary

Abstract

Describes the request and response details of this Moosend API endpoint to get a campaign summary

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you want to get a summary of.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - contains all the following information for the campaign:

    • CampaignID - the ID of the campaign.

    • ABVersion - if the campaign is an A/B split test campaign, this displays which campaign version was sent. This is null for a regular campaign.

    • CampaignName - the name of the campaign.

    • CampaignSubject - the subject line of the campaign.

    • MailingLists - a list that contains the email lists or segments that that campaign is sent to.

      • MailingListID - the ID of the email list.

      • SegmentID - the ID of the selected segment. This is 0 if there is no segment selected.

    • CampaignDeliveredOn - the date-time the campaign was delivered.

    • To - the date-time the measurement ended.

    • From - the date-time the measurement started.

    • TotalOpens - the total number of email opens.

    • UniqueOpens - the total number of unique email opens.

    • TotalBounces - the total number of email bounces.

    • TotalComplaints - the total number of complaints.

    • TotalForwards - the total number of email forwards for the campaign using the Forward to a friend personalization tag.

    • UniqueForwards - the total number of unique forwards for the campaign using the Forward to a friend personalization tag.

    • TotalUnsubscribes - the total number of unsubscribed recipients for the campaign.

    • TotalLinkClicks - the total number of link clicks.

    • UniqueLinkClicks - the total number of unique link clicks.

    • Sent - the total number of campaign emails sent.

    • CampaignIsArchived - specifies whether the campaign has been archived. A campaign older than three months gets archived and only high-level data about the campaign becomes available.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "CampaignID": "13cffeee-0b8c-4610-8e0d-efa7bd44be32",
    "ABVersion": null,
    "CampaignName": "test image path",
    "CampaignSubject": "test image path",
    "MailingLists": [
      {
        "MailingListID": "84bs231b131-367a-4d73-af11-01b4b45d3f54",
        "SegmentID": 0
      }
    ],
    "CampaignDeliveredOn": "/Date(1464256291013+0100)/",
    "To": "/Date(1465481260987+0100)/",
    "From": "/Date(1464256291013+0100)/",
    "TotalOpens": 1340,
    "UniqueOpens": 780,
    "TotalBounces": 4,
    "TotalComplaints": 0,
    "TotalForwards": 55,
    "UniqueForwards": 55,
    "TotalUnsubscribes": 7,
    "TotalLinkClicks": 976,
    "UniqueLinkClicks": 711,
    "Sent": 2550,
    "CampaignIsArchived": false
  }
}

Get campaign activity by location

Abstract

Describes the request and response details of this Moosend API endpoint to get campaign activity by location.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you want to get the activity by location of.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and Analytics information for the campaign:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of results that are included in the response.

      • TotalPageCount - the total number of pages in your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • Analytics - a list of countries where the campaign opens occurred. It contains the following information for each country:

      • Context - the country code.

      • ContextName - the name of the country.

      • TotalCount - the total number of campaign opens.

      • UniqueCount - The total number of unique campaign opens.

      • ContextDescription - this is null for this case.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 0,
      "CurrentPage": 1,
      "TotalResults": 0,
      "TotalPageCount": 0,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Analytics": [
      {
        "Context": "  ",
        "ContextName": null,
        "TotalCount": 1,
        "UniqueCount": 1,
        "ContextDescription": null
      }
    ]
  }
}

Get campaign link activity

Abstract

Describes the request and response details of this Moosend API endpoint to get campaign link activity.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 0,
      "CurrentPage": 1,
      "TotalResults": 0,
      "TotalPageCount": 0,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Analytics": [
      {
        "Context": "http://someUrl.com/",
        "ContextName": null,
        "TotalCount": 34,
        "UniqueCount": 30,
        "ContextDescription": null
      },
      {
        "Context": "http://someUrl.com/product1/",
        "ContextName": null,
        "TotalCount": 95,
        "UniqueCount": 67,
        "ContextDescription": null
      },
      {
        "Context": "http://someUrl.com/product2/",
        "ContextName": null,
        "TotalCount": 102,
        "UniqueCount": 78,
        "ContextDescription": null
      },
      {
        "Context": "https://twitter.com/myCompany",
        "ContextName": null,
        "TotalCount": 89,
        "UniqueCount": 89,
        "ContextDescription": null
      }
    ]
  }
}

Get A/B campaign summary

Abstract

Describes the request and response details of this Moosend API endpoint to get a summary of an A/B campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the A/B campaign that you want to get a summary of.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the A/B split test campaign:

    • CampaignID - the ID of the winning campaign version.

    • A - an object that contains the following information for campaign A:

      • CampaignID - the ID of campaign A.

      • ABVersion - the version of the campaign. This is 0 for campaign A and 1 for campaign B.

      • CampaignName - the name of the campaign.

      • CampaignSubject - the subject of the campaign.

      • MailingLists - a list that contains the details of email lists and any segments that that campaign is sent to:

        • Campaign - this is null for this case.

        • ID - the ID of the email list.

        • Name - the name of the email list.

        • ActiveMemberCount - the number of active members in the email list.

        • BouncedMemberCount - the number of bounced emails in the email list.

        • RemovedMemberCount - the number of members removed from the email list.

        • UnsubscribedMemberCount - the number of emails that unsubscribed from the email list.

        • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2, and for deleted, this is 3.

        • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list. The parameters are:

          • ID - the ID of the custom field.

          • Name - the name of the custom field

          • Context - the context of the custom field. This is null if the field type is not SingleSelectDropDown.

          • IsRequired - this is true if the custom field is required and false if it is not.

          • Type - the data type of the custom field. Possible values: 0 for text, 1 for number, 2 for dateTime, 3 for SingleSelectDropDown, and 5 for checkbox.

        • CreatedBy - the IP address used to create the email list.

        • CreatedOn - the date-time the email list was created.

        • UpdatedBy - the IP address used to update the email list.

        • UpdatedOn - the date-time the requested email list was updated.

        • ImportOperation - an object that contains the details of the latest import operation performed in the requested email list. This is blank if there was no import done.

          • ID - the ID of the import operation.

          • DataHash - a globally unique identifier (GUID) for the import operation

          • Mappings - the data mappings used for the specific import operation.

          • EmailNotify - this is null if the import operation notification email was not selected to be sent

          • CreatedOn - the date-time when the import operation was created.

          • StartedOn - the date-time when the import operation was stated.

          • CompletedOn - the date-time when the import operation was completed.

          • TotalInserted - the total number of inserted emails.

          • TotalUpdated - the total number of updated emails.

          • TotalUnsubscribed - the total number of unsubscribed emails.

          • TotalInvalid - the total number of invalid emails.

          • TotalIgnored - the total number of ignored emails.

          • TotalDuplicate - the total number of duplicate emails.

          • TotalMembers - the total number of members that were selected to be imported.

          • Message - the message of the import operation. This is null if successful.

          • Success - this is true if successful.

          • SkipNewMembers - this is false if the skip new members option was not selected before the import operation began.

        • Segment - a list of segments containing all the following information for each segment. This is null if the campaign was not sent to a email list segment.

          • ID - the ID of the segment.

          • Name - the name of the segment.

          • MatchType - specifies how subscribers are returned by your segment based on matching criteria. Possible values are:

            • 0 - for All. Returns subscribers that match all the given criteria.

            • 1 - for Any. Returns subscribers that match any of the given criteria.

          • Criteria - contains a list with information for each selected criterion selected for the segment.

          • CreatedBy - the IP address used to create the segment.

          • CreatedOn - the date-time the requested segment was created.

          • UpdatedBy - the IP address used to update the segment.

          • UpdatedOn - the date-time the segment was updated.

          • FetchType - the selected fetch type for the selected segment criteria. Possible values are:

            • 0 - for all segment criteria.

            • 1 - for the top segment criteria.

            • 2 - for the top percent segment criteria.

          • Description - contains a string representation of all the selected filters, MatchType criteria, and FetchType criteria.

      • CampaignDeliveredOn - the date-time the campaign was delivered.

      • To - the date-time the measurement ended.

      • From - the date-time the measurement started.

      • TotalOpens - the total number of email opens.

      • UniqueOpens - the total number of unique email opens.

      • TotalBounces - the total number of email bounces.

      • TotalComplaints - the total number of complaints.

      • TotalForwards - the total number of email forwards for the campaign using the Forward to a friend personalization tag.

      • UniqueForwards - the total number of unique forwards for the campaign using the Forward to a friend personalization tag.

      • TotalUnsubscribes - the total number of unsubscribed recipients for the campaign.

      • TotalLinkClicks - the total number of link clicks.

      • UniqueLinkClicks - the total number of unique link clicks.

      • Sent - the total number of campaign emails sent.

      • CampaignIsArchived - specifies whether the campaign has been archived. A campaign older than three months gets archived and only high-level data about the campaign becomes available.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production use