Skip to content

Instantly share code, notes, and snippets.

@pedroadaodev
Last active February 15, 2018 11:27
Show Gist options
  • Save pedroadaodev/971a757a241db5c0f43389012b64d11f to your computer and use it in GitHub Desktop.
Save pedroadaodev/971a757a241db5c0f43389012b64d11f to your computer and use it in GitHub Desktop.
MailChimp API add contact to list
// mailchimp API add member to list
// http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/
// how to get my Id List
// https://kb.mailchimp.com/lists/manage-contacts/find-your-list-id
var listId = "myListId";
var url = "https://us3.api.mailchimp.com/3.0/lists/" + listId + "/members";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", apiKey);
// Serialize our concrete class into a JSON String
// ADD multiple emails
//var stringPayload = "{\"members\": [{\"email_address\": \"myemail@server.com\", \"status\": \"subscribed\", \"language\": \"pt_PT\"}], \"update_existing\": true}";
// ADD one email
var stringPayload = "{\"email_address\":\"myemail@server.com\", \"status\":\"subscribed\", \"language\": \"pt_PT\"}";
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
var results = response.Content.ReadAsStringAsync().Result;
<div>@results</div>
}
else
{
<div>error code : @response.StatusCode</div>
<div>error : @response</div>
<div>error Headers : @response.Headers</div>
<div>error Content : @response.Content.ReadAsStringAsync().Result</div>
//Console.WriteLine($"ERROR (HTTP Status = {response.StatusCode}");
}
}
catch (HttpRequestException e)
{
<div>EXCEPTION: @e</div>
// Handle exception.
}
catch (Exception e)
{
<div>EXCEPTION: @e.Message</div>
//Console.WriteLine(e.Message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment