MailChimp is a fantastic service for creating email campaigns and managing your email lists. And they offer a relatively robust API that you can implement to dynamically send out emails and manage and sync your email lists, or create campaigns.
In this post, I will be showing how to implement their API to dynamically subscribe users to your email lists using C#. While there are several 3rd party implementations in .NET and other programming languages, I will be showing how to implement the API using just C# and the built in HTTP libraries.
Create an API Key
The first thing you want to do is to head on over to MailChimp and create an API key to begin to make requests against the API.
Head on over to the account tab in the menu dropdown. After, in the menu that appears, under the Extras tab, select the API Keys link.
By default, you do not have an API key created. In the API keys page you can create multiple API keys and manage them as well.
Create the Request object
After you have your API key created, you'll need to create your Request object, which is essentially a JSON object.
var subscribeRequest = new
{
email_address = email,
status = "subscribed",
merge_fields = new
{
FNAME = firstname,
LNAME = lastname
}
};
Note that this request object is specially for subscribing users to an email list, and each different API method will have their own specific properties and values. The one's listed above are for the most part required in order to make a request.
Serialize the data
In order to make the request, you will first need to serialize the JSON data. And we can do that with the following function.
var requestJson = JsonConvert.SerializeObject(subscribeRequest);
The following is a generic function that you can use to make any call to any MailChimp API endpoint.
Making the request
private string CallMailChimpApi(string method, string requestJson, string key)
{
var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "<datacenter>", method);
byte[] dataStream = Encoding.UTF8.GetBytes(requestJson);
var responsetext = string.Empty;
WebRequest request = HttpWebRequest.Create(endpoint);
WebResponse response = null;
try
{
request.ContentType = "application/json";
SetBasicAuthHeader(request, "anystring", key); // BASIC AUTH
request.Method = "POST";
request.ContentLength = dataStream.Length;
Stream newstream = request.GetRequestStream();
newstream.Write(dataStream, 0, dataStream.Length);
newstream.Close();
response = request.GetResponse();
// get the result
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
JsonSerializer json = new JsonSerializer();
JObject content = JObject.Parse(reader.ReadToEnd());
responsetext = reader.ReadToEnd();
}
response.Close();
}
catch(WebException ex)
{
using (var sr = new StreamReader(response.GetResponseStream()))
{
responsetext = sr.ReadToEnd();
}
}
return responsetext;
}
A few things to note about the above function.
<datacenter>: The datacenter is unique to your API key. It will be the part in your API after the '-' character. Secondly, notice that the authentication method is set to basic and can be set using the following function.
public void SetBasicAuthHeader(WebRequest request, string username, string password)
{
string auth = username + ":" + password;
auth = Convert.ToBase64String(Encoding.Default.GetBytes(auth));
request.Headers["Authorization"] = "Basic " + auth;
}
The password in this case will be your API key and you do not need to specify any particular username. Any string will do. The rest of the function is relatively self-explanatory and can be used over and over with the various different API methods. And to make the final request, you can call the function with the following parameters.
CallMailChimpApi("lists/<listid>/members/", requestJson, apiKey);
All you will need to set is the listid that you are targeting and your API key, which we created up above. And that is how you would create a new subscriber using the MailChimp API.
Other API endpoints will function in the exact same manner and will only require you create the appropriate JSON request objects and the correct endpoint URL's. Read the following here to check out what else you can do with the API.
The platform recently underwent a large shift in its pricing structure, which may or may not affect many organizations using it. Check out the following post to read more on MailChimp pricing.
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
Last updated on: