REST Email Marketing API Documentation

Example 5 — Download and parse a mailing report

The following example gets the deliverability data for a mailing. If there is more data than comes with the initial download, the remaining data is requested. Then each row is processed to check the results for responses that the email address is invalid. You might feed this data back into your CRM or other system to indicate that the email address you received from the recipient is not correct. This is just one example of what could be done with the reports. The full SMTP response from the mail server is recorded in the database and can be seen in the web interface.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.VisualBasic.FileIO;

private static async Task RestExample5(HttpClient client)
{
	string url = "https://example.com/API/Rest/Mailings/Report?accountName=acme&login=ApiUser&mailingTitle=DecSpecials&reportType=Deliverability";
	string result;

	using (var request = new HttpRequestMessage(HttpMethod.Get, url))
	{
		request.Headers.Add("Password", "YOUR_PASSWORD");
		using (HttpResponseMessage response = await client.SendAsync(request))
		{
			response.EnsureSuccessStatusCode();
			result = await response.Content.ReadAsStringAsync();
		}
	}

	if (!result.TrimStart().StartsWith("{"))
	{
		Console.WriteLine(result);
		return;
	}

	using (JsonDocument report = JsonDocument.Parse(result))
	{
		JsonElement root = report.RootElement;
		int totalRows = root.GetProperty("totalRows").GetInt32();
		JsonElement initialRows = root.GetProperty("userData");
		var rows = new List<List<string>>();

		if (totalRows > initialRows.GetArrayLength())
		{
			string downloadGuid = root.GetProperty("downloadGuid").GetString();
			string fileUrl = "https://example.com/API/Rest/Utility/GetFile?accountName=acme&login=ApiUser&fileNameGuid=" + downloadGuid;
			string tabSeparatedData = await client.GetStringAsync(fileUrl);

			using (var parser = new TextFieldParser(new StringReader(tabSeparatedData)))
			{
				parser.SetDelimiters("\t");
				parser.HasFieldsEnclosedInQuotes = true;
				parser.ReadLine(); // Skip the header row.
				while (!parser.EndOfData)
					rows.Add(new List<string>(parser.ReadFields()));
			}
		}
		else
		{
			rows = JsonSerializer.Deserialize<List<List<string>>>(initialRows.GetRawText());
		}

		foreach (List<string> row in rows)
			if (row.Count > 2 && row[2] == "Unknown user")
				Console.WriteLine("Email address " + row[0] + " is invalid");
	}
}
			
# encoding: utf-8
require 'rest-client'
require 'json'
require 'open-uri'
require 'csv'

url = "https://example.com/api/rest/mailings/Report?accountName=acme&login=ApiUser&mailingTitle=DecSpecials&reportType=Deliverability"
   
headers = {'password':'YOUR_PASSWORD'}
resp = RestClient.get url, headers
if resp.code != 200
	puts "Mailing report failed!"
	puts resp.code
	exit
end

if resp.body[0] == "{"
	data = JSON.parse(resp.body)
	rowsReturned = data["userData"].length
	#check if we can just use the data we have been given so far, or if we need to go download the rest.
	if data["totalRows"] > rowsReturned
		url = "https://example.com/api/rest/Utility/GetFile?accountName=acme&login=ApiUser&fileNameGuid=" + data["downloadGuid"] 
		URI.open(url) do |data1|
			File.open("C:/temp/RubyDownload.txt", "wb") do |file1|
				file1.write(data1.read)
			end
		end
		
		CSV.foreach("C:/temp/RubyDownload.txt", { :col_sep => "\t" }) do |row|
			if row[2] == "Unknown user"
				puts "email address: " + row[0] + " is invalid"
			end
		end
	else
		for row in data["userData"]
			if row[2] == "Unknown user"
				puts "email address: " + row[0] + " is invalid"
			end
		end
	end
else
	puts resp.body
end
							
import requests
import json
import csv


def mailingStats():
    url = "https://example.com/api/rest/mailings/Report?accountName=acme&login=ApiUser&mailingTitle=July19Specials&reportType=Deliverability"
    
    headers = {'password':'YOUR_PASSWORD'}
    resp = requests.get(url, headers=headers)
    if resp.status_code != 200:
        print("Mailing report failed!")
        print(resp.status_code)
        return
    if resp.text[0] == "{":
        data = json.loads(resp.text)
        rowsReturned = len(data["userData"])
        #check if we can just use the data we have been given so far, or if we need to go download the rest.
        if data["totalRows"] > rowsReturned:
            url = "https://example.com/api/rest/Utility/GetFile?accountName=acme&login=ApiUser&fileNameGuid=" + data["downloadGuid"] 
            resp = requests.get(url)
            if resp.status_code != 200:
                print("Get file failed!")
                print(resp.status_code)
                return
            #The data comes as tab-separated CSV, so now we need to parse it.
            with open('c:/temp/PythonDownload.txt', 'wb') as f:
                f.write(resp.content)
            with open('c:/temp/PythonDownload.txt') as f:
                reader = csv.reader(f, delimiter='\t')
                for row in reader:
                    if row[2] == "Unknown user":
                        print("email address: " + row[0] + " is invalid")
        else:
            for row in data["userData"]:
                if row[2] == "Unknown user":
                    print("email address: " + row[0] + " is invalid")
    else:
        print(resp.text)

mailingStats()