|

|  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 開発キット 2

無限のカスタマイズ

OMI 開発キット 2

$69.99

Omi AIネックレスで会話を音声化、文字起こし、要約。アクションリストやパーソナライズされたフィードバックを提供し、あなたの第二の脳となって考えや感情を語り合います。iOSとAndroidでご利用いただけます。

  • リアルタイムの会話の書き起こしと処理。
  • 行動項目、要約、思い出
  • Omi ペルソナと会話を活用できる何千ものコミュニティ アプリ

もっと詳しく知る

Omi Dev Kit 2: 新しいレベルのビルド

主な仕様

OMI 開発キット

OMI 開発キット 2

マイクロフォン

はい

はい

バッテリー

4日間(250mAH)

2日間(250mAH)

オンボードメモリ(携帯電話なしで動作)

いいえ

はい

スピーカー

いいえ

はい

プログラム可能なボタン

いいえ

はい

配送予定日

-

1週間

人々が言うこと

「記憶を助ける、

コミュニケーション

ビジネス/人生のパートナーと、

アイデアを捉え、解決する

聴覚チャレンジ」

ネイサン・サッズ

「このデバイスがあればいいのに

去年の夏

記録する

「会話」

クリスY.

「ADHDを治して

私を助けてくれた

整頓された。"

デビッド・ナイ

OMIネックレス:開発キット
脳を次のレベルへ

最新ニュース
フォローして最新情報をいち早く入手しましょう

最新ニュース
フォローして最新情報をいち早く入手しましょう

thought to action.

Based Hardware Inc.
81 Lafayette St, San Francisco, CA 94103
team@basedhardware.com / help@omi.me

Company

Careers

Invest

Privacy

Events

Manifesto

Compliance

Products

Omi

Wrist Band

Omi Apps

omi Dev Kit

omiGPT

Personas

Omi Glass

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

Ambassadors

Resellers

© 2025 Based Hardware. All rights reserved.