Email management

How to Send Transactional Emails with Mailchimp API in Node.js? (w Codes and Examples)

Anjali Arya
November 22, 2024
Master sending transactional emails in Node.js using Mailchimp API. Comprehensive guide with codes and examples for seamless integration. Optimize your email workflow now with SuprSend and Mailchimp API in Node.
TABLE OF CONTENTS

This guide explores the process of establishing a programmatic Node.js-based transactional email delivery system using Mailchimp's transactional email API, shedding light on potential challenges and offering insights into optimizing this crucial aspect of communication. 

Prerequisites

Before delving into the hands-on tutorial, ensure you meet the following prerequisites:

  1. General familiarity with JavaScript and Node.js.
  2. Understanding of the async/await syntax in JavaScript.
  3. Proficiency in using the node command in the command line.
  4. Awareness of Express.js functionality and how middlewares operate in Express.js.

Now, let's proceed with setting up Mailchimp node.js for email sending. Let's dive in.

How to Send Emails with Nodejs and Mailchimp API?

To send transactional emails using Mailchimp Node.js, the initial step is to register for a free Mailchimp account. Follow their step-by-step email API integration guide outlined below.

Register and Generate an API Key on Mailchimp

  1. Begin by registering for a free Mailchimp account using a valid email address and a password.
  2. After registration and account setup, create a new audience (list) in Mailchimp.
  3. Generate the API key from your account settings. Copy and securely store the API key for future use.

Setting Up a Node.js Script to Send Emails with Mailchimp

To initiate a new Node.js application using npm, execute the following commands:

  
   npm init -y
        
    

The `-y` flag will set default values. Next, set the API key created in the `mailchimp.env` file, and ensure it's added to `.gitignore`:

  
   echo "export MAILCHIMP_API_KEY='YOUR_API_KEY'" > mailchimp.env && echo "mailchimp.env" >> .gitignore && source ./mailchimp.env
        
    

Ensure to replace `YOUR_API_KEY` with the generated API key from the previous step. Afterward, install the `axios` npm package:

  
   npm i --save axios
        
    

This command adds the latest version of the package to `package.json` and installs it locally in the `node_modules` folder.

Now, let's write code to test sending emails with Mailchimp:

  
    const axios = require('axios');

    function getMessage() {
      const body = 'This is a test email using Mailchimp from Node.js';
      return {
        to: [{ email: 'you@domain.com' }],
        from: { email: 'your@email.com', name: 'Your Name' },
        subject: 'Test email with Node.js and Mailchimp',
        text: body,
        html: `${body}`,
      };
    }

    async function sendEmail() {
      try {
        const response = await axios.post(
          'https://.api.mailchimp.com/3.0/messages',
          getMessage(),
          {
            headers: {
              Authorization: `Basic ${Buffer.from(`anystring:${process.env.MAILCHIMP_API_KEY}`).toString('base64')}`,
              'Content-Type': 'application/json',
            },
          }
        );
        console.log('Test email sent successfully');
        console.log(response.data);
      } catch (error) {
        console.error('Error sending test email');
        console.error(error.response.data);
      }
    }

    (async () => {
      console.log('Sending test email');
      await sendEmail();
    })();
        
    

Replace <dc> in the Mailchimp API URL with your Mailchimp data center code, and ensure to replace MAILCHIMP_API_KEY with the actual API key you generated from your Mailchimp account.

After running this script with `node send-test-email.js`, you should receive a test email in your inbox.

Creating an Order Confirmation Email API in Node.js Using Mailchimp

For a practical example, let's transform the script into an API using Express.js. Install Express.js:

  
    npm i --save express
        
    

Create two files: `index.js` for the web server and `email.js` for the email service. Here's the `index.js`:

  
    const express = require('express');
    const email = require('./email');

    const app = express();
    const port = 3000 || process.env.PORT;

    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));

    app.get('/', (req, res) => {
      res.json({ message: 'alive' });
    });

    app.post('/api/email/order-confirmation', async (req, res, next) => {
      try {
        res.json(await email.sendOrderConfirmation(req.body));
      } catch (err) {
        next(err);
      }
    });

    app.use((err, req, res, next) => {
      const statusCode = err.statusCode || 500;
      console.error(err.message, err.stack);
      res.status(statusCode).json({ 'message': err.message });
      return;
    });

    app.listen(port, () => {
      console.log(`Example API listening at http://localhost:${port}`);
    });
        
    

This Express server sets up a route for a simple "alive" message at the root and an API endpoint for sending order confirmation emails. The error handling middleware is also included.

Now, let's examine the structure of our email.js file. I utilized the Stripo.email free plan to create a mock order confirmation email, incorporating their provided template. Below is our email.js file, which assembles the email and dispatches it through Mailchimp:

  
    const axios = require('axios');

    function getOrderConfirmationEmailHtml(customerName, orderNr) {
      // HTML template for the order confirmation email
      // (omitted for brevity due to its length)
    }

    function getMessage(emailParams) {
      return {
        to: [{ email: emailParams.toEmail }],
        from: { email: 'your@email.com', name: 'Your Name' },
        subject: 'We have got your order, you will receive it soon',
        text: `Hey ${emailParams.name}, we have received your order ${emailParams.orderNr}. We will ship it soon`,
        html: getOrderConfirmationEmailHtml(emailParams.name, emailParams.orderNr),
      };
    }

    async function sendOrderConfirmation(emailParams) {
      try {
        const response = await axios.post(
          'https://.api.mailchimp.com/3.0/messages',
          getMessage(emailParams),
          {
            headers: {
              Authorization: `Basic ${Buffer.from(`anystring:${process.env.MAILCHIMP_API_KEY}`).toString('base64')}`,
              'Content-Type': 'application/json',
            },
          }
        );
        return { message: `Order confirmation email sent successfully for orderNr: ${emailParams.orderNr}` };
      } catch (error) {
        const message = `Error sending order confirmation email or orderNr: ${emailParams.orderNr}`;
        console.error(message);
        console.error(error.response.data);
        return { message };
      }
    }

    module.exports = {
      sendOrderConfirmation,
    };
        
    

Replace <dc> in the Mailchimp API URL with your Mailchimp data center code, and ensure to replace MAILCHIMP_API_KEY with the actual API key you generated from your Mailchimp account.

Let's delve into the functionality of email.js:

  1. Integration with Mailchimp: The module begins by importing the axios mail module and setting the API key using `mailchimp.setApiKey()`.
  2. Order Confirmation HTML Template: The `getOrderConfirmationEmailHtml` function holds the extensive HTML template for the order confirmation email. It dynamically incorporates the customer's name and order number.
  3. Assembling the Email Message: The `getMessage` function constructs the email message with details such as recipient, sender, subject, text, and HTML body. The HTML body is generated using the previously defined template.
  4. Sending the Order Confirmation Email: The `sendOrderConfirmation` function orchestrates the entire process. It calls the `send` method on the `mailchimpmail` module, passing the parameters obtained from `getMessage`. Any errors are caught, logged, and an appropriate response is sent back.
  5. Module Export: Finally, only the `sendOrderConfirmation` function is exposed from this module.

Once both files are correctly set up, you can launch the server with `node index.js`. Testing the order confirmation email API can be done with a cURL command:

  
    curl -i -X POST -H 'Accept: application/json' \
        -H 'Content-type: application/json' http://localhost:3000/api/email/order-confirmation \
        --data '{"name":"YourName", "orderNr": "12344", "toEmail": "yourEmail@gmail.com"}'
        
    

A successful response should display a 200 status, and you should find the confirmation email in your inbox.

Congratulations! The fundamental order confirmation email functionality is operational. The HTML template, though lengthy, can be replaced using Mailchimps's Dynamic templates.

While the method described above is functional, it may have certain limitations, and that's where SuprSend can offer valuable enhancements:

  1. Scalability Challenges: For scaling the nodejs email sending task, two primary options are presented. One is utilizing a queue system like RabbitMQ, employing producers and consumers to handle messages efficiently. Alternatively, a serverless FaaS (function-as-a-service) approach, using platforms like AWS Lambda or Vercel, provides a low-maintenance scaling solution. The order placement logic can asynchronously call this API, ensuring scalability with minimal resource concerns. Further exploration into scalability, costs, and potential hosting options is encouraged. The current implementation may face challenges in handling a rapidly increasing number of orders. As the order volume grows, the synchronous nature of the nodejs email sending process might lead to potential bottlenecks, affecting overall system scalability.
  2. Limited Monitoring and Analytics: The existing solution may lack comprehensive monitoring and analytics capabilities, making it challenging to gather insights into email delivery performance, recipient engagement, and potential issues.
  3. Maintenance Overhead: Managing and maintaining the nodejs email sending infrastructure, including handling errors and ensuring deliverability, might require ongoing effort and expertise.
  4. Integration Complexity: Integrating and maintaining multiple components, such as the email template, Mailchimp, and error handling, could introduce complexities and potential points of failure.
  5. Cost Considerations: Depending on the email volume, the costs associated with using Mailchimp and managing the infrastructure may become a concern.

For all these challenges, you can use SuprSend as a possible parent email infrastructure coupled with your product in Node.js to get started with any email provider such as Mailchimp. You can install and integrate SuprSend Node SDK to set up your product email notification infrastructure. Save yourselves from multiple vendor API integrations and email configurations for lifetime with these 4 easy steps

SuprSend Communication flow
Written by:
Anjali Arya
Product & Analytics, SuprSend
Get a powerful notification engine with SuprSend
Build smart notifications across channels in minutes with a single API and frontend components
Implement a powerful stack for your notifications
By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.