Introduction to Mailchimp API
- Mailchimp offers a powerful API that allows developers to interact with various Mailchimp features programmatically. The API can manage audiences, campaigns, and reports directly from your application.
- In this guide, we will focus on managing email lists, also known as audiences, using Mailchimp API with Node.js.
Install Required Packages
- Initialize your project and install the necessary packages. You need `axios` or `node-fetch` for API requests. In this example, we'll use `axios`.
npm init -y
npm install axios
Set Up Environment Variables
- Create a `.env` file in your project root to store your Mailchimp API key securely. Add your API key and server prefix in this file.
MAILCHIMP_API_KEY=<YOUR_API_KEY>
MAILCHIMP_SERVER_PREFIX=<YOUR_SERVER_PREFIX>
Initialize Axios for API Requests
- Configure Axios to include the necessary authorization header and base URL. The base URL will be your server prefix combined with the Mailchimp API domain.
require('dotenv').config();
const axios = require('axios');
const apiKey = process.env.MAILCHIMP_API_KEY;
const serverPrefix = process.env.MAILCHIMP_SERVER_PREFIX;
const axiosInstance = axios.create({
baseURL: `https://${serverPrefix}.api.mailchimp.com/3.0/`,
headers: {
'Content-Type': 'application/json',
'Authorization': `apikey ${apiKey}`
}
});
List Existing Audiences
- Create a function to fetch all audiences associated with your Mailchimp account. This will involve a GET request to the `lists` endpoint.
async function listAudiences() {
try {
const response = await axiosInstance.get('/lists');
console.log(response.data);
} catch (error) {
console.error('Error fetching list:', error);
}
}
listAudiences();
Create a New Audience
- You can create an audience by POSTing to the `/lists` endpoint. Prepare a function to send required data like name, contact information, and permissions.
async function createAudience(name, contact, permissionReminder) {
const data = {
name,
contact,
permission_reminder: permissionReminder,
email_type_option: true,
campaign_defaults: {
from_name: 'Your Name',
from_email: 'your-email@example.com',
subject: '',
language: 'en'
}
};
try {
const response = await axiosInstance.post('/lists', data);
console.log('Created new audience:', response.data);
} catch (error) {
console.error('Error creating audience:', error);
}
}
// Example usage
createAudience('New Audience', {
company: 'Company Name',
address1: 'Address',
city: 'City',
state: 'State',
zip: 'Zip',
country: 'Country'
}, 'Permission reminder text');
Add Members to an Audience
- To add members to an audience, you need to send a POST request to `/lists/{list_id}/members` with email and other information.
async function addMemberToAudience(listId, email, status = 'subscribed') {
const data = {
email_address: email,
status
};
try {
const response = await axiosInstance.post(`/lists/${listId}/members`, data);
console.log('Added member:', response.data);
} catch (error) {
console.error('Error adding member:', error);
}
}
// Example usage
addMemberToAudience('audience_id', 'newmember@example.com');
Update Member Information
- You can update a member’s information by sending a PATCH request to `/lists/{list_id}/members/{subscriber_hash}`. The `subscriber_hash` is a MD5 hash of the lowercase version of the member’s email.
const crypto = require('crypto');
async function updateMemberInfo(listId, email, newInfo) {
const subscriberHash = crypto.createHash('md5').update(email.toLowerCase()).digest('hex');
try {
const response = await axiosInstance.patch(`/lists/${listId}/members/${subscriberHash}`, newInfo);
console.log('Updated member info:', response.data);
} catch (error) {
console.error('Error updating member info:', error);
}
}
// Example usage
updateMemberInfo('list_id', 'member@example.com', { merge_fields: { FNAME: 'FirstName', LNAME: 'LastName' } });
Remove Members from an Audience
- To remove a member, you need to send a DELETE request to `/lists/{list_id}/members/{subscriber_hash}`.
async function removeMemberFromAudience(listId, email) {
const subscriberHash = crypto.createHash('md5').update(email.toLowerCase()).digest('hex');
try {
await axiosInstance.delete(`/lists/${listId}/members/${subscriberHash}`);
console.log('Member removed successfully');
} catch (error) {
console.error('Error removing member:', error);
}
}
// Example usage
removeMemberFromAudience('list_id', 'member@example.com');
Handle Errors and Practices
- Always include error handling in your functions to catch and diagnose issues effectively.
- Log the requests and responses when debugging to better understand the data flow.
Conclusion
- Using Node.js and the Mailchimp API, you can effectively manage email lists, automate audience creation, modify member data, and more, thereby streamlining your email marketing workflows programmatically.
- This guide provided the core techniques necessary to interact with Mailchimp audiences; extend these examples further based on your project’s needs.