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.

private class ReportData
{
	public string downloadGuid;
	public int totalRows;
	public System.Collections.Generic.List<System.Collections.Generic.List<string>> userData = new System.Collections.Generic.List<System.Collections.Generic.List<string>>();
}

private static void RestExample5()
{
	try
	{
		string url = "http://www.example.com/api/rest/mailings/Report?accountName=acme&login=ApiUser&mailingTitle=DecSpecials&reportType=Deliverability";

		System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
		request.Headers.Add("Password", "df6dg5gd78gd");
		string data;
		using (System.Net.WebResponse response = request.GetResponse())
			using (Stream responseStream = response.GetResponseStream())
				using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
					data = reader.ReadToEnd();

		if (data[0] == '{')
		{
			System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
			ReportData rd = jss.Deserialize<ReportData>(data);

			int rowsReturned = rd.userData.Count;

			List<List<string>> results;

			//check if we can just use the data we have been given so far, or if we need to go download the rest.

			if (rd.totalRows > rowsReturned)
			{
				url = "http://www.example.com/api/rest/Utility/GetFile?accountName=acme&login=ApiUser&fileNameGuid=" + rd.downloadGuid.ToString();

				System.Net.WebClient client = new System.Net.WebClient();
				client.DownloadFile(url, @"C:\temp\RestDownload.txt");

				results = new List<List<string>>();

				// To use the TextFieldParser a reference to the Microsoft.VisualBasic assembly has to be added to the project. 
				using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser("c:\\temp\\RestDownload.txt"))
				{
					parser.SetDelimiters(new string[] { "\t" });
					parser.HasFieldsEnclosedInQuotes = false;

					// Skip over header line.
					parser.ReadLine();

					while (!parser.EndOfData)
					{
						List<string> values = new List<string>();

						string[] readFields = parser.ReadFields();
						if (readFields != null)
							values.AddRange(readFields);
						results.Add(values);
					}
				}
			}
			else
				results = rd.userData;

			foreach (List<string> row in results)
			{
				// Do something with the data. In this case we'll look for invalid email addresses.

				if (row[2] == "Unknown user")
					System.Console.WriteLine("email address: " + row[0] + " is invalid");
			}
		}
		else
		{
			// some error occurred, the details of which will be in the returned string
			System.Console.WriteLine(data);
		}
	}
	catch (System.Exception e)
	{
		System.Diagnostics.Debug.Fail(e.Message);
	}
}
# encoding: utf-8
require 'rest-client'
require 'json'
require 'open-uri'
require 'csv'

url = "http://www.example.com/api/rest/mailings/Report?accountName=acme&login=ApiUser&mailingTitle=DecSpecials&reportType=Deliverability"
   
headers = {'password':'xvcjhdv6sfdysfdhjsfd'}
resp = RestClient.get url, headers
if resp.code != 200
	puts "Mailing report failed!"
	puts resp.status_code
	return
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 = "http://www.example.com/api/rest/Utility/GetFile?accountName=acme&login=ApiUser&fileNameGuid=" + data["downloadGuid"] 
		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 = "http://www.example.com/api/rest/mailings/Report?accountName=acmet&login=ApiUser&mailingTitle=July19Specials&reportType=Deliverability"
    
    headers = {'password':'34teg4543fg34'}
    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 = "http://www.example.com/api/rest/Utility/GetFile?accountName=acme&login=ApiUser&fileNameGuid=" + data["downloadGuid"] 
            resp = requests.get(url, headers=headers)
            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()

Share this: