|

|  How to Manage Email Lists Using Mailchimp API in Node.js

How to Manage Email Lists Using Mailchimp API in Node.js

October 31, 2024

Learn to manage email lists seamlessly with Mailchimp API in Node.js. This guide simplifies list operations and enhances your marketing efficiency.

How to Manage Email Lists Using Mailchimp API in Node.js

 

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.

 

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action

team@basedhardware.com

company

careers

events

invest

privacy

products

omi

omi dev kit

personas

resources

apps

bounties

affiliate

docs

github

help