Integrate Mailchimp Campaigns with Notion Databases

This developer documentation provides a step-by-step guide to create an integration between the Notion API and the Mailchimp API using JavaScript. The integration syncs Mailchimp email campaigns and subscriber lists with a Notion database.

Prerequisites

  • Node.js installed on your machine
  • A Mailchimp account
  • A Notion account

Step 1: Get Your API Keys

Mailchimp API Key

  1. Log in to your Mailchimp account.
  2. Navigate to your profile by clicking on your account name in the lower-left corner.
  3. Go toย Profile.
  4. Click on theย Extrasย dropdown and selectย API keys.
  5. Click onย Create A Key.
  6. Copy the generated API key.

Notion API Key

  1. Log in to your Notion account.
  2. Go toย Notion Integrations.
  3. Click onย New Integration.
  4. Fill in the required details and clickย Submit.
  5. Copy the generatedย Internal Integration Token.

Step 2: Set Up Your Notion Database

  1. Create a new database in Notion with the following properties:
  • Campaign Nameย (Title)
  • Nameย (Text)
  • Emailย (Email)
  1. Share the database with your integration:
  • Click on theย three dots in the top-right corner of the page.
  • Underย Connections, click on Connect to and search for your integration and invite it.

Step 3: Project Structure

This step is not necessary but we suggest projects to be structured like so:

project-root/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ config/
โ”‚   โ”‚   โ””โ”€โ”€ mailchimp.js
โ”‚   โ”‚   โ””โ”€โ”€ notion.js
โ”‚   โ”œโ”€โ”€ integrations/
โ”‚   โ”‚   โ”œโ”€โ”€ mailchimpIntegration.js
โ”‚   โ”‚   โ””โ”€โ”€ notionIntegration.js
โ”‚   โ”œโ”€โ”€ main.js
โ”œโ”€โ”€ .env
โ”œโ”€โ”€ package.json

Step 4: Create .env file

Create a .env file in your project directory with the following content, replacing the placeholders with your actual credentials:

NOTION_TOKEN='you_notion_api_key'
MAILCHIMP_API_KEY='your_mailchimp_api_key'
NOTION_DATABASE_ID='your_database_id'

Step 5: Packages

Install the required Node.js packages using the following command:

npm install @notionhq/client dotenv

Create a package.json file and add the following:

{
    "name": "mailchimp_notion_integration",
    "version": "1.0.0",
    "main": "src/main.js",
    "scripts": {
      "start": "node src/main.js"
    },
    "dependencies": {
      "@notionhq/client": "^1.0.0",
      "dotenv": "^8.2.0"
    }
  }

Step 6: Configure Mailchimp and Notion API clients

Create mailchimp.js to set up the Mailchimp API client. Ensure your credentials are being passed here.

// mailchimp.js
const Mailchimp = require('mailchimp-api-v3');
const dotenv = require('dotenv');

dotenv.config();

const mailchimp = new Mailchimp(process.env.MAILCHIMP_API_KEY);

module.exports = mailchimp;

Repeat to create notion.js :

// notion.js
const { Client } = require('@notionhq/client');
const dotenv = require('dotenv');

dotenv.config();

const notion = new Client({ auth: process.env.NOTION_TOKEN });
const databaseId = process.env.NOTION_DATABASE_ID;

module.exports = { notion, databaseId };

Step 7: Set Up Integrations

Create mailchimpIntegrations.js to fetch campaigns and subscribers from Mailchimp:

// mailchimpIntegration.js
const mailchimp = require('../config/mailchimp');

async function getMailchimpCampaigns() {
  try {
    const response = await mailchimp.get('/campaigns');
    const campaigns = response.campaigns;
    return campaigns.map(campaign => ({
      id: campaign.id,
      list_id: campaign.recipients.list_id,
      campaign_name: campaign.settings.title
    }));
  } catch (error) {
    console.error('Error fetching Mailchimp campaigns:', error);
    return [];
  }
}

async function getMailchimpSubscribers(list_id) {
  try {
    const response = await mailchimp.get(`/lists/${list_id}/members`);
    return response.members.map(member => ({
      name: member.full_name,
      email: member.email_address
    }));
  } catch (error) {
    console.error('Error fetching Mailchimp subscribers:', error);
    return [];
  }
}

module.exports = { getMailchimpCampaigns, getMailchimpSubscribers };

Additionally, create notionIntegrations.js to populate the Notion Database:

// notionIntegration.js
const { notion, databaseId } = require('../config/notion');

async function addToNotionDatabase(databaseId, campaignName, name, email) {
  try {
    await notion.pages.create({
      parent: { database_id: databaseId },
      properties: {
        'Campaign Name': {
          title: [
            {
              text: {
                content: campaignName
              }
            }
          ]
        },
        'Name': {
          rich_text: [
            {
              text: {
                content: name
              }
            }
          ]
        },
        'Email': {
          rich_text: [
            {
              text: {
                content: email
              }
            }
          ]
        }
      }
    });
  } catch (error) {
    console.error('Error adding to Notion database:', error);
  }
}

module.exports = { addToNotionDatabase };

Step 8: Main Script

Create a main.js file that uses the modules created above to execute the integration logic.

require('dotenv').config();

const { getMailchimpCampaigns, getMailchimpSubscribers } = require('./integrations/mailchimpIntegration');
const { addToNotionDatabase } = require('./integrations/notionIntegration');

const NOTION_DATABASE_ID = process.env.NOTION_DATABASE_ID;

async function fillNotionDatabase() {
  const campaigns = await getMailchimpCampaigns();
  
  for (const campaign of campaigns) {
    const subscribers = await getMailchimpSubscribers(campaign.list_id);
    
    for (const subscriber of subscribers) {
      await addToNotionDatabase(NOTION_DATABASE_ID, campaign.campaign_name, subscriber.name, subscriber.email);
      console.log(`Added to Notion: Campaign: ${campaign.campaign_name}, Name: ${subscriber.name}, Email: ${subscriber.email}`);
    }
  }
}

fillNotionDatabase();

Step 9: Run the Integration

Execute the integration script by running the following command:

npm start 

๐Ÿ”‘

Customize the code to match your Notion database structure and desired properties for each campaign or subscriber. Add error handling and further customization as needed for your specific requirements.