REST Email Marketing API Documentation

Example 1

In this example we show the code to send an email to multiple people. We'll start by preparing the recipients — first by creating some demographics to hold information, and then by importing the recipients. Next, we'll create the mailing, assign the audience, and queue the mailing to be distributed.

Once a demographic has been created it doesn't need to be re-created or maintained, so this example isn't that useful. The developer should know whether the demographic exists or not. However, testing for the demographic and creating it if it doesn't exist is shown for completeness.

There is some limited error checking in this code, but for a production system more should be done.

In our simple example mailing, we will dynamically merge the two demographic columns we defined to build an email specific to the recipient. The mail merge tag DbColumn is defined in this documentation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;

private class DemographicsDataOutput
{
	public string ColumnName;
}

private class RecipientAddManyResult
{
	public string emailAddress;
	public int recipientId;
	public string importMessage;
}

private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
{
	IncludeFields = true,
	PropertyNameCaseInsensitive = true
};

private static async Task<string> PostAsync(HttpClient client, string url, object body)
{
	using (HttpResponseMessage response = await client.PostAsJsonAsync(url, body))
	{
		response.EnsureSuccessStatusCode();
		return await response.Content.ReadAsStringAsync();
	}
}

private static async Task<string> SendWithPasswordAsync(HttpClient client, HttpMethod method, string url)
{
	using (var request = new HttpRequestMessage(method, url))
	{
		request.Headers.Add("Password", "YOUR_PASSWORD");
		using (HttpResponseMessage response = await client.SendAsync(request))
		{
			response.EnsureSuccessStatusCode();
			return await response.Content.ReadAsStringAsync();
		}
	}
}

private static async Task RestExample1(HttpClient client)
{
	string results = await SendWithPasswordAsync(
		client,
		HttpMethod.Get,
		"https://example.com/API/Rest/Demographics?accountName=acme&login=ApiUser");

	List<DemographicsDataOutput> demographics =
		JsonSerializer.Deserialize<List<DemographicsDataOutput>>(results, JsonOptions);

	bool foundName = demographics.Any(row => row.ColumnName == "SalespersonName");
	bool foundEmail = demographics.Any(row => row.ColumnName == "SalespersonEmail");

	if (!foundName)
	{
		results = await PostAsync(client, "https://example.com/API/Rest/Demographics", new
		{
			accountName = "acme",
			login = "ApiUser",
			password = "YOUR_PASSWORD",
			columnName = "SalespersonName",
			dataType = "String50",
			displayInSearchResults = false,
			exportWithReports = true
		});
		Console.WriteLine(results);
	}

	if (!foundEmail)
	{
		results = await PostAsync(client, "https://example.com/API/Rest/Demographics", new
		{
			accountName = "acme",
			login = "ApiUser",
			password = "YOUR_PASSWORD",
			columnName = "SalespersonEmail",
			dataType = "String100",
			displayInSearchResults = false,
			exportWithReports = true
		});
		Console.WriteLine(results);
	}

	results = await PostAsync(client, "https://example.com/API/Rest/Recipients/AddMany", new
	{
		accountName = "acme",
		login = "ApiUser",
		password = "YOUR_PASSWORD",
		importType = "AddAndUpdate",
		culture = "en-US",
		demographics = new[]
		{
			new[] { "EmailAddress", "Name", "SalespersonName", "SalespersonEmail" },
			new[] { "bob@example.com", "Bob Smith", "Joe Jones", "joe@example.com" },
			new[] { "fred.smith@example.com", "Fred Smith", "Ralph Karns", "ralph@example.com" }
		}
	});

	if (!results.TrimStart().StartsWith("["))
	{
		Console.WriteLine("Error on AddMany: " + results);
		return;
	}

	List<RecipientAddManyResult> importResults =
		JsonSerializer.Deserialize<List<RecipientAddManyResult>>(results, JsonOptions);
	foreach (RecipientAddManyResult row in importResults)
		Console.WriteLine(row.emailAddress + " " + row.importMessage);

	// Delete the unsent mailing, if it exists, so this example can be run again.
	results = await SendWithPasswordAsync(
		client,
		HttpMethod.Delete,
		"https://example.com/API/Rest/Mailings/Remove?accountName=acme&login=ApiUser&mailingTitle=CES%202019b");
	Console.WriteLine(results);

	results = await PostAsync(client, "https://example.com/API/Rest/Mailings/Create", new
	{
		accountName = "acme",
		login = "ApiUser",
		password = "YOUR_PASSWORD",
		mailingTitle = "CES 2019b",
		htmlBody = "[-NameEmail-]:<br/><br/>Nice to meet you at CES. Your regional salesperson is [-DbColumn SalespersonName-] ([-DbColumn SalespersonEmail-]).<br/><br/>Cheers<br/>Joe Smith",
		charsetId = "1252",
		subject = "Our meeting at CES",
		bodyLanguageId = "1033",
		trackAllLinks = true,
		unsubscribeTopic = "Apology"
	});
	if (!results.StartsWith("Success"))
	{
		Console.WriteLine("Error on mailing create: " + results);
		return;
	}

	results = await PostAsync(client, "https://example.com/API/Rest/Mailings/Audience", new
	{
		accountName = "acme",
		login = "ApiUser",
		password = "YOUR_PASSWORD",
		mailingTitle = "CES 2019b",
		replaceExisting = true,
		recipients = new[] { "bob@example.com", "fred.smith@example.com" }
	});
	if (!results.TrimStart().StartsWith("{"))
	{
		Console.WriteLine("Error on mailing audience: " + results);
		return;
	}

	results = await SendWithPasswordAsync(
		client,
		HttpMethod.Put,
		"https://example.com/API/Rest/Mailings/Queue?accountName=acme&login=ApiUser&mailingTitle=CES%202019b");
	Console.WriteLine(results);
}
			
# encoding: utf-8
require 'rest-client'
require 'json'

url = "https://example.com/api/rest/Demographics?accountName=acme&login=ApiUser"
response = RestClient.get url, {:Password => "YOUR_PASSWORD"}
if response.code != 200
    puts "Get demographics failed"
    puts response
    exit
else
    data = JSON.parse(response.body)
end	

foundName = false
foundEmail = false

for row in data
    if row['ColumnName'] == "SalespersonName"
        foundName = true
    end
    if row['ColumnName'] == "SalespersonEmail"
        foundEmail = true
    end
end

if foundName == false
    url = 'https://example.com/api/rest/Demographics'
    data = {"accountName":"acme","login":"ApiUser","password":"YOUR_PASSWORD",'columnName':'SalespersonName', 'dataType':'String50', 'displayInSearchResults':false, 'exportWithReports':true}
    response = RestClient.post url, data.to_json, {"Content-Type": "application/json"}
    if response.code != 200
        puts "Add SalespersonName demographic failed"
        puts response.code
        exit
    elsif response.body == "Success"
        puts "Created demographic SalespersonName"
    else
        puts response.body
        exit
    end
else
    puts "Demographic SalespersonName already exists."
end

if foundEmail == false
    url = 'https://example.com/api/rest/Demographics'
    data = {"accountName":"acme","login":"ApiUser","password":"YOUR_PASSWORD",'columnName':'SalespersonEmail', 'dataType':'String100', 'displayInSearchResults':false, 'exportWithReports':true}
    response = RestClient.post url, data.to_json, {"Content-Type": "application/json"}
    if response.code != 200
        puts "Create demographic SalespersonEmail failed!"
        puts response.code
        exit
    elsif response.body == "Success"
        puts "Created demographic SalespersonEmail"
    else
        puts response.body
        exit
    end
else
    puts "Demographic SalespersonEmail already exists."
end

url = 'https://example.com/api/rest/Recipients/AddMany'
data = {"accountName":"acme","login":"ApiUser","password":"YOUR_PASSWORD","importType":"AddAndUpdate","culture":"en-US", "demographics":[["EmailAddress", "Name", "SalespersonName", "SalespersonEmail"],["bob@aol.com","Bob Smith", "Joe Jones", "joe@example.com"], ["fred.smith@aol.com","Fred Smith", "Ralph Karns", "r.karns@example.com"]]}
response = RestClient.post url, data.to_json, {"Content-Type": "application/json"}
if response.code != 200
    puts "AddMany failed"
    puts response.body
    exit
elsif response.body[0] == "["
    results = JSON.parse(response.body)
    for row in results
        puts row['emailAddress'] + " " + row['importMessage']
    end
else
    puts "Error on AddMany!: " + response.body
end
    
#try to delete the mailing, to assist with testing. Once the mailing has been sent it cannot be deleted.
url = 'https://example.com/api/rest/Mailings/Remove?accountName=acme&login=ApiUser&mailingTitle=CES%202019e'
response = RestClient.delete(url, {:Password => "YOUR_PASSWORD"})
if response.code != 200
    puts "Mailing delete failed"
    puts response.code
    exit
elsif response.body.length > 6 and response.body == "Success"
    puts  "Mailing deleted successfully"
else
    puts "Error on mailing delete!: " + response.body
end

url = 'https://example.com/api/rest/Mailings/Create'
data = {"accountName":"acme", "login":"ApiUser", "password":"YOUR_PASSWORD", "mailingTitle":"CES 2019e",
        'htmlBody':'[-NameEmail-]:<br/><br/>Nice to meet your at the CES show. Please look for contact from your regional salesperson, [-DbColumn SalespersonName-]. If you want to reach out immediately, use email address: [-DbColumn SalespersonEmail-].<br/><br/>Cheers<br/>Joe Smith',
        'charsetId':'1252', 'subject':'Our meeting at CES','bodyLanguageId':'1033', 'trackAllLinks':true,
        'unsubscribeTopic':'Apology'}
response = RestClient.post url, data.to_json, {"Content-Type": "application/json"}
if response.code != 200
    puts "Mailing create failed"
    puts response.code
    exit
elsif response.body.length > 6 and response.body[0..6] == "Success"
    puts "Mailing created successfully."
else
    puts "Error on mailing create!: " + response.body
end

url = 'https://example.com/api/rest/Mailings/Audience'
data = {"accountName":"acme","login":"ApiUser","password":"YOUR_PASSWORD", "mailingTitle":"CES 2019e", "replaceExisting":true, "recipients":["bob@aol.com", "fred.smith@aol.com"]}
response = RestClient.post url, data.to_json, {"Content-Type": "application/json"}
if response.code != 200
    puts "Assigning the audience failed"
    puts response.code
    exit
elsif response.body[0] == "{"
    puts "Mailing audience assigned."
else
    puts "Error on mailing audience!: " + response.body
end
    
url = 'https://example.com/api/rest/Mailings/Queue?accountName=acme&login=ApiUser&mailingTitle=CES%202019e&queueTime=2019-07-07'
response = RestClient.put url, "", {:Password => "YOUR_PASSWORD"}
if response.code != 200
    puts "Mailing queue failed"
    puts response.code
    exit
elsif response.body[0] == "{"
    puts "Mailing queued successfully. Here are the stats:"
    puts response.body
else
    puts "Error on mailing queue!: " + response.body
    exit
end

import requests
import json

url = "https://example.com/api/rest/Demographics?accountName=acme&login=ApiUser"
headers = {'Password':'YOUR_PASSWORD'}
resp = requests.get(url, headers=headers)
if resp.status_code != 200:
    print("Retrieve of demographics failed!")
    print(resp.status_code)
else:
    data = json.loads(resp.text)

foundName = False
foundEmail = False

for row in data:
    if row['ColumnName'] == "SalespersonName":
        foundName = True
    if row['ColumnName'] == "SalespersonEmail":
        foundEmail = True

if foundName == False:
    url = 'https://example.com/api/rest/Demographics'
    data = {"accountName":"acme","login":"ApiUser","password":"YOUR_PASSWORD",'columnName':'SalespersonName', 'dataType':'String50', 'displayInSearchResults':False, 'exportWithReports':True}
    resp = requests.post(url, json=data, headers={"Content-Type": "application/json"})
    if resp.status_code != 200:
        print("Create of demographic SalespersonName failed!")
        print(resp.status_code)
    elif resp.text == "Success":
        print ("Created demographic SalespersonName")
    else:
        print(resp.text)
else:
    print ("Demographic SalespersonName already exists.")

if foundEmail == False:
    url = 'https://example.com/api/rest/Demographics'
    data = {"accountName":"acme","login":"ApiUser","password":"YOUR_PASSWORD",'columnName':'SalespersonEmail', 'dataType':'String100', 'displayInSearchResults':False, 'exportWithReports':True}
    resp = requests.post(url, json=data, headers={"Content-Type": "application/json"})
    if resp.status_code != 200:
        print("Create demographic SalespersonEmail failed!")
        print(resp.status_code)
    elif resp.text == "Success":
        print ("Created demographic SalespersonEmail")
    else:
        print(resp.text)
else:
    print ("Demographic SalespersonEmail already exists.")

url = 'https://example.com/api/rest/Recipients/AddMany'
data = {"accountName":"acme","login":"ApiUser","password":"YOUR_PASSWORD", 'importType':'AddAndUpdate', 'culture':'en-US', 'demographics':[['EmailAddress', 'Name', 'SalespersonName', 'SalespersonEmail'],
                                                                                                                            ['bob@aol.com','Bob Smith', 'Joe Jones', 'joe@example.com'],
                                                                                                                            ['fred.smith@aol.com','Fred Smith', 'Ralph Karns', 'r.karns@example.com']]}
resp = requests.post(url, json=data, headers={"Content-Type": "application/json"})
if resp.status_code != 200:
    print("AddMany failed")
    print(resp.status_code)
elif resp.text[0] == "{":
    results = json.loads(resp.text)
    for row in results:
        print ( row['emailAddress'] + " " + row['importMessage'])
else:
    print ("Error on AddMany!: " + resp.text)
    
#try to delete the mailing, to assist with testing. Once the mailing has been sent it cannot be deleted.
url = 'https://example.com/api/rest/Mailings/Remove?accountName=acme&login=ApiUser&mailingTitle=CES%202019'
resp = requests.delete(url, headers=headers)
if resp.status_code != 200:
    print("Mailing delete failed")
    print(resp.status_code)
elif len(resp.text) > 6 and resp.text == "Success":
    print ( "Mailing deleted successfully")
else:
    print ("Error on mailing delete!: " + resp.text)

url = 'https://example.com/api/rest/Mailings/Create'
data = {"accountName":"acme", "login":"ApiUser", "password":"YOUR_PASSWORD", "mailingTitle":"CES 2019",
        'htmlBody':'[-NameEmail-]:

Nice to meet your at the CES show. Please look for contact from your regional salesperson, [-DbColumn SalespersonName-]. If you want to reach out immediately, use email address: [-DbColumn SalespersonEmail-].

Cheers
Joe Smith', 'charsetId':'1252', 'subject':'Our meeting at CES','bodyLanguageId':'1033', 'trackAllLinks':True, 'unsubscribeTopic':'Apology'} resp = requests.post(url, json=data, headers={"Content-Type": "application/json"}) if resp.status_code != 200: print("Mailing create failed") print(resp.status_code) elif len(resp.text) > 6 and resp.text[0:7] == "Success": print ( "Mailing created successfully.") else: print ("Error on mailing create!: " + resp.text) url = 'https://example.com/api/rest/Mailings/Audience' data = {"accountName":"acme","login":"ApiUser","password":"YOUR_PASSWORD", "mailingTitle":"CES 2019", "replaceExisting":True, "recipients":["bob@aol.com", "fred.smith@aol.com"]} resp = requests.post(url, json=data, headers={"Content-Type": "application/json"}) if resp.status_code != 200: print("Assigning the audience failed") print(resp.status_code) elif resp.text[0] == "{": print ( "Mailing audience assigned.") else: print ("Error on mailing audience!: " + resp.text) url = 'https://example.com/api/rest/Mailings/Queue?accountName=acme&login=ApiUser&mailingTitle=CES%202019' resp = requests.put(url, headers=headers) if resp.status_code != 200: print("Mailing queue failed") print(resp.status_code) elif resp.text[0] == "{": print ( "Mailing queued successfully. Here are the stats:") print (resp.text) else: print ("Error on mailing queue!: " + resp.text)