ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

How to add a subscriber to MailChimp using C#

Written by
Published on
Modified on
Filed under
How to add a subscriber to MailChimp using C#

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 software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

a
asif
10/22/2019 7:05:41 PM
Can you please send me code of mail chimp api, add contact using api in C#
Walt
10/23/2019 10:13:59 AM
Hello there. Thank you for the comment and for checking out the post. You can actually use the same code and just update the method and parameters. The request objects and flow would still be the same process. If you'd like, I can publish another post with that specific example. Do let me know and thanks again.
H
Herman
3/3/2020 6:59:20 AM
Hello, is there anyone with an full example of adding a new email to a mailchimp list in asp.net with VB as code language. (not C#) It looks like it is not possible to convert c# to VB and get a working example.
A
9/21/2020 5:41:33 AM
Hi. Thanks for the instructions. You never use the variables json and content within //get the result. Did you mean to convert the response to JSON?
s
srini
10/5/2020 12:25:56 AM
the above sample code will useful to create new contact in Mailchimp ? I have .net web application on click of button i want to move my contacts to Mailchimp.
X
XyUser
12/2/2020 10:58:07 PM
Can you please provide the code to add subscriber to specific interest group when adding the subscriber.

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks