Working With The MailChimp API In .NET: The MailChimpManager Class

As noted in Part 2 of this series, central to the MailChimp.NET.V3 library is the MailChimpManager class.

This class acts as a context, marshalling all the methods and other classes that are used to create, populate, send, retrieve and parse a response to the MailChimp API.

In other words, we create an instance of MailChimpManager, and through that, we can conduct whatever interaction we want to conduct with the MailChimp API.

As we saw in Part 2, the purest form of this is to declare a private member very high up in scope:

using System.Web.Mvc;
using MailChimp.Net;

namespace MailChimpNet.Controllers
{
	public class MailChimpController : Controller
	{
		private static MailChimpManager Manager = new MailChimpManager();
	}
}
Throughout this series, I will be using as ASP.NET MVC application to demonstrate this code. However, everything I note here will work in any type of .NET project.

A list of successfully sent campaigns

Let’s take a look at a basic example. I’m going to create an ActionResult that pulls a list of the last 10 blog newsletter campaigns I have sent.

To start, I need to declare the ActionResult method as an async Task, because the MailChimp.NET.V3 library operates asynchronously and we’re making requests to a third-party API that may take a while to complete.

using MailChimp.Net;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace MailChimpNetDemo.Controllers
{
    public class MailChimpController : Controller
    {
        private static readonly MailChimpManager Manager = new MailChimpManager();

        public async Task<ActionResult> SentCampaigns()
        {
            return View();
        }
    }
}

Note that I have added the System.Threading.Tasks namespace, so I can call async and use the Task class as my return value.

Set parameters with the CampaignRequest class

Now I’m ready to use MailChimpManager to get a list of sent campaigns. First, I need to set the parameters for the campaigns I want listed:

  • They must be for my Newsletter list;
  • They have to have been sent; and
  • I want only the 10 most recent campaigns.

I set those parameters by declaring and populating a CampaignRequest class.

In MailChimp.NET.V3, most read requests are accomplished by filtering the request via a {Something}Request class, where {Something} is the name of the object you’re trying to retrieve.

In this case, we’re trying to get a collection of Campaign objects, so we instantiate a CampaignRequest class with the filters we want to run on this query.

If we were attempting to get a collection of Member objects, we would create a MemberRequest instance and set its properties to filter our requests.

And so on, and so on; there are {Something}Request filter classes for pretty much every kind of object that can be listed by a MailChimp API method, be they related to lists, members, campaigns, templates, whatever.

All of these {Something}Request filters are part of the MailChimp.Net.Core namespace, so we need to add that to our code:

using MailChimp.Net;
using MailChimp.Net.Core;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace MailChimpNetDemo.Controllers
{
    public class MailChimpController : Controller
    {
        private static readonly MailChimpManager Manager = new MailChimpManager();

        public async Task<ActionResult> SentCampaigns()
        {
            var options = new CampaignRequest
            {
                ListId = "abc123",
                Status = CampaignStatus.Sent,
                SortOrder = CampaignSortOrder.DESC,
                Limit = 10
            };
        }
    }
}

Make the request and pass the model

OK, we’re ready to actually call to the MailChimp API for our list of sent campaigns.

To do that, we will use the MailChimpManager.Campaigns.GetAllAsync method, passing to it the CampaignRequest instance we made in the section above.

The last section will describe how this method, and most MailChimp.NET.V3 methods, are defined. For now, let’s focus on the implementation.

I’m going to wrap this request in a try-catch block.

According to the notes on the class that defines the GetAllAsync method, I can encounter several different kinds of exceptions.

UriFormatException, NotSupportedException and TypeLoadException are all unlikely to occur, because they would be thrown by parts of the MailChimp.NET.V3 library as part of how it goes about its business.

ArgumentNullException or ArgumentOutOfRangeException will be thrown if we fail to include a properly populated CampaignRequest object; if we don’t set the ListId property of the CampaignRequest instance; or if we intentionally set another value in that instance to nonsense.

All other errors — failure to connect to the MailChimp API; rejection of our API key or other restrictions on access; failure to parse the response — will raise a MailChimpException. I’ll want to make note of these exceptions apart from the others, since any error in the MailChimp API itself is something I’ll want to deal with quickly.

Specifically, I am going to return good, old-fashoned HTTP status codes when things go wrong: a 504 error for MailChimpException, and a 503 error for everything else.

So here’s all of the controller code:

using MailChimp.Net;
using MailChimp.Net.Core;
using System;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace MailChimpNetDemo.Controllers
{
    public class MailChimpController : Controller
    {
        private static readonly MailChimpManager Manager = new MailChimpManager();

        public async Task<ActionResult> SentCampaigns()
        {
            var options = new CampaignRequest
            {
                ListId = "abc123",
                Status = CampaignStatus.Sent,
                SortOrder = CampaignSortOrder.DESC,
                Limit = 10
            };

            try
            {
                var model = await Manager.Campaigns.GetAllAsync(options);
                return View(model);
            }
            catch (MailChimpException mce)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadGateway, mce.Message);
            }
            catch(Exception ex)
            {
                return new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable, ex.Message);
            }
        }
    }
}

Note that to make use of the HttpStatusCode enum, I have to import the System.Net namespace.

Now I can make the view.

Create the view

We’re now ready to create the view. To do that, I choose Add View > Empty (without model), because I’m a little too lazy to wire things up so that Visual Studio knows I want to work with the MailChimp.NET.V3 models.

I do, however, create a partial view, because I am working with the Bootstrap template that’s automatically created with a new ASP.NET MVC project.

This template is just a standard foreach loop:

@model IEnumerable<MailChimp.Net.Models.Campaign>
@{
    ViewBag.Title = "Sent Campaigns";
}

<h2>Sent Campaigns</h2>

<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>Sent Date</th>
            <th>Emails Sent</th>
            <th>View</th>
        </tr>
    </thead>
    <tbody>
        @foreach(var campaign in Model)
        {
            <tr>
                <td>@campaign.Id</td>
                <td>@campaign.SendTime</td>
                <td>@campaign.EmailsSent</td>
                <td><a href="@campaign.ArchiveUrl" target="_viewCampaign">View &raquo;</a></td>
            </tr>
        }
    </tbody>
</table>

On Line 1, I declare that the model for this view will be an IEnumerable of the MailChimp.Net.Models.Campaign.

On Line 18, I use a simple foreach loop to output some basic parameters of each Campaign: Its ID, the day it was sent, the number of people it was sent to, and a link to view the content that was sent.

Here’s what it looks like:

Screenshot of the view for the SentCampaigns method of the MailChimpController class.
Screenshot of the view for the SentCampaigns method of the MailChimpController class.

Methods as members

As promised above, this section describes how MailChimp.NET.V3 creates methods for calling MailChimp REST API endpoints.

You don’t need to read this section to follow this tutorial, and if you are relatively new to .NET, you probably want to skip this section.

Reading this section will help you understand how to find the correct methods to call the API endpoint you want. It will also help you identify the errors that a method in MailChimp.NET.V3 might throw.

The reason we only need to create an instance of MailChimpManager to interact with the API is because of the way MailChimp.NET.V3 is built.

Basically, every collection of method calls — such as, all the calls we would need to interact with our mailing lists, or the members of those lists, or our campaigns, or our templates, etc. — that are in the MailChimp API are represented as a member of the MailChimpManager class.

Want to access your lists? You’ll start by calling MailChimpManager.Lists. Want members? Those methods are grouped under MailChimpManager.Members. And so on.

The MailChimp.NET.V3 is built around four namespaces:

Core is set of classes that represent the transactional aspects of working with the MailChimp REST API. In here are classes that provide filtering of requests (that is, the ability to narrow your searches to date ranges, statuses, etc.).

Models are representations of each of the kinds of things you can get back from the MailChimp API: individual members, lists, the saved segments in a list, campaigns, etc.

Logic is the transactional part of each model. For example, almost all the models — Member, Campaign, List, etc. — have basic CRUD methods in the MailChimp API.

The classes in the Logic namespace allow you to conduct API calls and receive back an appropriate representation of the model you want. For example, GetAllAsync, which we used above, is a method of the CampaignLogic class.

That class, in turn, is leveraged by the MailChimpManager’s Campaigns member through the use of an interface. Interfaces exist for all the logic classes, so that the MailChimpManager can easily assume their functionality.

There is some ambiguity to the class names in MailChimp.NET.V3, so in a larger project with many assemblies, you may find that you have to be specific about what version of the Campaign or Member or List classes you mean.

Code and demo

That’s it for now. In the next (and probably last) installment, we’ll look at more operations we can conduct via the MailChimpManager class.

Github repo for this series: https://github.com/dougvdotcom/MailChimpNetDemo

I’ll have a place for working ASP.NET MVC demos up and running at some point; I just need to decide what I’m going to do about my old WebForms demos first.

Companion video

2 Comments

  1. Hi

    I have created Template in my mailchimp account.

    How to call this template from my C# code and mailchimp api

    can you help me

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Check out the Commenting Guidelines before commenting, please!
  • Want to share code? Please put it into a GitHub Gist, CodePen or pastebin and link to that in your comment.
  • Just have a line or two of markup? Wrap them in an appropriate SyntaxHighlighter Evolved shortcode for your programming language, please!