Netlify function to add contact to Mailjet

I’m trying to set up a newsletter subscription form with name=“newsletter” that takes just one input with name=“email” and adds the submitted email to Mailjet. I have Netlify environment variables set: MJ_APIKEY_PRIVATE, MJ_APIKEY_PUBLIC, and MJ_LIST_ID and the form with action=“/.netlify/functions/subscribeToMailjet”.

The content of subscribeToMailjet.js is the following:

const axios = require('axios');

exports.handler = async function(event, context) {
  try {
    if (event.httpMethod !== 'POST') {
      return {
        statusCode: 405,
        body: JSON.stringify({ message: 'Method Not Allowed' })
      };
    }

    const { email } = JSON.parse(event.body);

    if (!email) {
      return {
        statusCode: 400,
        body: JSON.stringify({ message: 'Missing email in request body' })
      };
    }

    const payload = {
      Email: email,
      ContactsLists: [process.env.MAILJET_LIST_ID],
    };

    const response = await axios.post(
      'https://api.mailjet.com/v3/REST/contact',
      payload,
      {
        auth: {
          username: process.env.MJ_APIKEY_PUBLIC,
          password: process.env.MJ_APIKEY_PRIVATE
        }
      }
    );

    return {
      statusCode: response.status,
      body: JSON.stringify({ message: 'Subscriber added successfully' })
    };
  } catch (error) {
    console.error('Error:', error);

    return {
      statusCode: error.response ? error.response.status : 500,
      body: JSON.stringify({ message: 'An error occurred' })
    };
  }
};

The form html is:

<form class="w-full email-form" name="newsletter" method="POST" netlify netlify-honeypot="bot-field" action="/.netlify/functions/subscribeToMailjet">
  <label for="email" class="sr-only"> Email </label>
  <div class="border border-gray-100 p-2 focus-within:ring sm:flex sm:items-center sm:gap-4">
    <input required type="email" name="email" id="email" placeholder="Enter your email address..." class="w-full border-none focus:border-transparent focus:ring-transparent" />
    <button type="submit" class="mt-1 w-full bg-teal-500 px-6 py-3 text-sm font-bold uppercase tracking-wide text-white transition-none hover:bg-teal-600 sm:mt-0 sm:w-auto sm:shrink-0">Sign Up</button>
  </div>
  <div class="hidden">
    <label>Don’t fill this out if you’re human: <input name="bot-field" /></label>
  </div>
</form>

This seems like it should be easy but I just can’t get it to work. Please tell me what I’m doing wrong.

Hi @pensive, thanks for posting.
It is possible the mailjet configuration might be causing problems.

In order to start debugging, kindly console log out all environment variables to see if they log values.

After you can comment out the mailjet code and just return from your function a regular message to see if you receive it on your frontend. That way you know your function is working then you can move to the next debugging step.

Also if the above works fine, kindly check your function logs from your Netlify UI dashboard by sending a request from the form. If there are any errors thrown the function logs will display it.
You can learn how to access the function logs by visiting the Netlify documentation link below

Finally just make sure that the environment variables are correctly set and that you’ve installed the axios package.

Let me know the outcome.
Thanks.

1 Like

Thank you for your reply. After many, many hours, I finally got it to work with the following:

const axios = require("axios");

exports.handler = async (event) => {
  const parsedData = new URLSearchParams(event.body);
  const dataObj = {};
  for (var pair of parsedData.entries()) {
    dataObj[pair[0]] = pair[1];
  }
  console.log("DataObj: ", dataObj);
  const email = dataObj.email;

  // Get environment variables
  const { MJ_APIKEY_PUBLIC, MJ_APIKEY_PRIVATE, MJ_LIST_ID } = process.env;

  // Create the contact in Mailjet
  try {
    const response = await axios.post(
      "https://api.mailjet.com/v3/REST/contact",
      {
        IsExcludedFromCampaigns: "false",
        Email: email,
      },
      {
        auth: {
          username: MJ_APIKEY_PUBLIC,
          password: MJ_APIKEY_PRIVATE,
        },
      }
    );

    // Add the contact to the contact list
    await axios.post(
      `https://api.mailjet.com/v3/REST/contactslist/${MJ_LIST_ID}/managemanycontacts`,
      {
        Action: "addnoforce", //addforce,addnoforce,remove
        Contacts: [
          {
            Email: email,
          },
        ],
      },
      {
        auth: {
          username: MJ_APIKEY_PUBLIC,
          password: MJ_APIKEY_PRIVATE,
        },
      }
    );

    return {
      statusCode: 200,
      body: JSON.stringify({
        message: "Contact added to Mailjet successfully",
      }),
    };
  } catch (error) {
    console.error("Error adding contact to Mailjet:", error);

    return {
      statusCode: 500,
      body: JSON.stringify({
        message: "Failed to add contact to Mailjet",
      }),
    };
  }
};

1 Like

Hi @pensive glad to know you finally got your problem solved.
Also thanks for sharing your solution. It will help others experiencing a similar problem in the future.

1 Like