> ## Documentation Index
> Fetch the complete documentation index at: https://developers.notion.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Integrate Mailchimp Campaigns with Notion Databases

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

export const developerConnectionsUrl = "https://app.notion.com/developers/connections";

## Prerequisites

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

## Step 1: Get Your API Keys

**Mailchimp API Key**

<Steps>
  <Step>
    Log in to your Mailchimp account.
  </Step>

  <Step>
    Navigate to your profile by clicking on your account name in the lower-left corner.
  </Step>

  <Step>
    Go to **Profile**.
  </Step>

  <Step>
    Click on the **Extras** dropdown and select **API keys**.
  </Step>

  <Step>
    Click on **Create A Key**.
  </Step>

  <Step>
    Copy the generated API key.
  </Step>
</Steps>

**Notion API Key**

<Steps>
  <Step>
    Log in to your Notion account.
  </Step>

  <Step>
    Go to <a href={developerConnectionsUrl}>Notion Connections</a>.
  </Step>

  <Step>
    Click on **New Connection**.
  </Step>

  <Step>
    Fill in the required details and click **Submit**.
  </Step>

  <Step>
    Copy the generated **Installation access token**.
  </Step>
</Steps>

## Step 2: Set Up Your Notion Database

<Steps>
  <Step>
    Create a new database in Notion with the following properties:

    * **Campaign Name** (Title)
    * **Name** (Text)
    * **Email** (Email)
  </Step>

  <Step>
    Share the database with your connection:

    * Click on the three dots in the top-right corner of the page.
    * Under **Connections**, click on **Connect to** and search for your connection and invite it.
  </Step>
</Steps>

## Step 3: Project Structure

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

```shell theme={null}
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:

```yaml YAML theme={null}
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:

```shell Shell theme={null}
npm install @notionhq/client dotenv
```

Create a `package.json` file and add the following:

```json JSON theme={null}
{
    "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.

```javascript JavaScript theme={null}
// 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` :

```javascript JavaScript theme={null}
// 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 Connections

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

```javascript JavaScript expandable theme={null}
// 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:

```javascript JavaScript expandable theme={null}
// 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 connection logic.

```javascript JavaScript expandable theme={null}
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 Connection

Execute the connection script by running the following command:

```shell Shell theme={null}
npm start
```

<Warning>
  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.
</Warning>
