Mailgun API


Author: Rachel
December 3, 2019 | 3 mins to read

Email campaigns can be pretty effective at keeping users engaged with your product or service. Campaigns can begin as soon as the user signs up. This blog post will detail how to subscribe users to a mailing list and send a templated email based on the form the user submits.

We will cover several features:

  • Serverless Functions
  • Netlify Functions
  • Mailgun Features & API
  • Integrating Mailgun with Netlify Forms Deployments

What are Serverless Functions?

Serverless functions is a cloud-computing execution model that allows cloud providers to provide the server infrastructure. The users do not need to be concerned about infrastructure configuration and deployment and can simply provide a set of conditions that may trigger the function to run.

I first saw Amazon's implementation of serverless functions implemented (AWS Lambda) for IoT devices, specifically Alexa. When the device interpretted an intent/request from the user, it would trigger a specific function to respond. Building out a program for a smart device became a series of functions that responded under certain circumstances. There was no need to develop complex API endpoints. Since then, it's increasingly used to handle simple and complex use cases alike.

Netlify Functions

Netlify functions are provided by Netlify via AWS' Lambda service, enabling you to interact with these functions like any other API service when you deploy your site for hosting on Netlify. It's the perfect solution for accessing the Mailgun API for sending out emails.

Mailgun Features & API

Mailgun has a generous free tier, making it a popular choice. It's API offers many features, including creating new mailing lists, adding members to mailing lists, sending emails based on pre-made templates, email validation, and statistics querying.

It can be used with a number of programming languages, including Ruby, Python, PHP, Java, C#, Go, and Node.js.

Integrating Mailgun with Netlify Forms Deployment

In addition to writing methods to call functions, Netlify makes it possible to automatically trigger functions when certain events happen. For a full list of available triggers, see this list. This is great for handling form submissions.

When a user submits a form, the submission-created event is triggered. If a function is found with this name, it will automatically run. This is where mailgun rest calls can be placed to take in form data, such as a name and email to add to a mailing list. This code block below checks the form the submission is associated with. If it is the newsletter form, it will add a new subscriber to the mailing list based on the information provided by the form data.

exports.handler = async (event, context, callback) => {
  const data = JSON.parse(event.body);
  const submissionData = data.payload;

  if (submissionData.form_name === "newsletter") {
    console.log("Processing a new newsletter subscriber for " + submissionData.data.email);

    // add to mailing list
    let list = mailgun.lists(`newsletter@${domain}`);

    let subscriber = {
      subscribed: true,
      address: submissionData.data.email,
      name: submissionData.data.name
    };
    console.log('Adding new subscriber to newsletter')
    list.members().create(subscriber, function(error, data) {
      if (error) {
        console.log("Error in adding a new subscriber.", error);
      }
      console.log("Subscriber added to newsletter mailing list");
    });
  }
}

After a form submission, it's also possible to send an email template based on the form submission. The code snippet below shows how this can be done.

let response;
try {
  /* Send email to recicipent */
  response = await mailgun.messages().send({
    to: `${submissionData.data.fullname} <${submissionData.data.email}>`,
    from: "email@test.com",
    subject: `Welcome Title`,
    template: "templateName"
  });
} catch (e) {
  console.log("Error in sending template.", e);
  return {
    statusCode: e.statusCode || 500,
    body: JSON.stringify({
      error: e.message
    })
  };
}

return {
  statusCode: 200,
  body: JSON.stringify({
    result: response.message
  })
};

Combining these two functions enables the addition of a new user to a mailing list followed by an email being automatically sent on submission. This can be used for a number of use cases, ranging from welcoming new users to your platform or newsletter to providing users with a series of emails to introduce them to the platform.

If you want to learn more, let's talk.