Learn how to Visually Build at Scale with Builder.io and Netlify Register now!

News & Announcements

Announcing the new Netlify Email Integration

News & Announcements

Announcing the new Netlify Email Integration

Given that 300 billion+ emails are sent daily, nearly every web developer likely deals with setting up email triggers including confirmation emails for event RSVPs, transaction emails for an e-commerce site, or auth codes for users logging into the site. To complicate matters further, there are hundreds of solutions to choose from, and this is typically the last thing devs want to deal with before deploying the site.

To streamline this process, we’ve implemented the new Netlify Email Integration, an out-of-the-box solution that enables users to customize email templates, inject dynamic parameters, and preview them during development.

With the Netlify Email Integration, devs can configure email triggers and edit templates all in the source code, which results in time savings and reduced complexity.

Getting Started

Step 1: Enabling the integration

Add it to your site via the Netlify app under Site Settings.

image

(app.netlify.com/sites/{your-sitename}/settings/emails)

Alternatively, add it to the netlify.toml as follows:

[[plugins]]
package = "@netlify/plugin-emails"

Step 2: Configuration

When enabling the plugin via Site Settings, you should add the required configuration variables to complete the configuration step.

If you are setting these variables manually, below are the environment variables required for the emails function to handle requests:

image

The variables can be added or edited in the Build & deploy settings in-app or through the Netlify CLI.

Step 3: Adding Templates

Now that the setup is complete, you can create an email directory ./emails in the base directory of your app or use a custom directory, as long as you define it in your Email Settings under ‘Email directory’.

Each email template should be stored under a folder name that represents the route of your template and the email file should be named index.html.

Here’s an example file structure for a subscriber email: /emails/subscribed/index.html:

repository-root or base directory/
├─ emails/
│ └─ subscribed/
│ └─ index.html
└─

If there are variables that need to be replaced in your email template when the email is triggered, please use the handlebars.js syntax and pass the arguments in the request as shown in Step 5 below.

Sample email with parameters:

<html>
<body>
<h1>Welcome, {{ NAME }}</h1>
<p>We hope you enjoy our super simple emails!</p>
<p>Thanks for subscribing!</p>
</body>
</html>

Style the template

You can also add custom styling to your templates by adding inline CSS blocks using the style attribute inside the HTML elements of the template index.html file.

<html>
<body
style="
font-family: 'Open Sans', 'Helvetica Neue', sans-serif;
margin: 0 auto;
"

>

<div
style="
background-color: white;
display: inline-block;
text-align: center;
"

>

<h1>{{ NAME }} has RSVP'd</h1>
<button style="border-radius: 10px;">
Visit dashboard
</button>
</div>
</body>
</html>

Step 4: Previewing email templates

The preview also generates a fetch snippet that contains the code required to send a request to the email handler for the template you are previewing. Use the Netlify CLI to launch a preview and generate this code.

  1. Ensure you have the latest version of Netlify CLI installed:
npm install netlify-cli -g
  1. Build your project.
netlify build
  1. Launch Netlify Dev to start a development environment that can run your email preview:
netlify dev
  1. Visit http://localhost:8888/.netlify/functions/emails/_preview to launch the preview.

The preview endpoint is not available in production and is only made available locally through Netlify Dev.

  1. Select your email template.

image

Step 5: Triggering an Email

When you preview your email template using the process above, Netlify generates a fetch code snippet.

image

To trigger an email directly from your project code, copy and paste this snippet into your project and populate the parameters for your email.

Create a Netlify Function to send the email

Because the snippet generated in the preview contains an environment variable, NETLIFY_EMAILS_SECRET, we recommend pasting the code snippet into a Netlify Function to avoid sharing sensitive information in client-side code.

You can learn more about the format of a Netlify Function call on the Build functions page. The function file should be in your netlify/functions directory. Following the fetch code example below, this example file’s path would be netlify/functions/triggerSubscribeEmail.ts.

import { Handler } from "@netlify/functions";
import fetch from "node-fetch";

const handler: Handler = async function (event) {
if (event.body === null) {
return {
statusCode: 400,
body: JSON.stringify("Payload required"),
};
}

const requestBody = JSON.parse(event.body) as {
subscriberName: string;
subscriberEmail: string;
inviteeEmail: string;
};

//automatically generated snippet from the email preview
//sends a request to an email handler for a subscribed email
await fetch(`${process.env.URL}/.netlify/functions/emails/subscribed`, {
headers: {
"netlify-emails-secret": process.env.NETLIFY_EMAILS_SECRET as string,
},
method: "POST",
body: JSON.stringify({
from: requestBody.inviteeEmail,
to: requestBody.subscriberEmail,
subject: "You've been subscribed",
parameters: {
name: requestBody.subscriberName,
email: requestBody.subscriberEmail,
},
}),
});

return {
statusCode: 200,
body: JSON.stringify("Subscribe email sent!"),
};
};

export { handler };

Next, you'll add an event in your code to call this Netlify Function.

Call the Netlify Function from an event

There are many approaches you can take to triggering an email. For example:

  • a user clicks a button requesting information, subscribing to a newsletter, or updating their profile

  • a user scrolls to the bottom of a blog post so you trigger an email to send them more information on that post subject or other posts

  • a data event has reached a certain amount and you would like an email sent to notify your users

Here’s an example of the code to attach the email trigger to a Subscribe button in a Next.js app. In this React example, the parameters for the template are set using user input from the form on the page. With this process, you can populate the parameters of your email templates with any data being passed to your site, like a form or data from API calls to a user database.

export default function Subscribe() {
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const target = event.target as typeof event.target & {
name: { value: string };
email: { value: string };
};

const data = {
subscriberName: target.name,
subscriberEmail: target.email,
};
//call to the Netlify Function you created
fetch("./.netlify/functions/triggerSubscribeEmail", {
method: "POST",
body: JSON.stringify({
subscriberName: data.subscriberName,
subscriberEmail: data.subscriberEmail,
inviteeEmail: "info@netlify.com",
}),
});
};
return (
<div className="subscribe-form-container">
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input type="text" id="name" name="name" required />
<label htmlFor="email">Email</label>
<input type="text" id="email" name="email" required />
<button type="submit">Subscribe</button>
</form>
</div>
);
}

When the event is triggered, this invokes the Netlify Function and the fetch call to an email handler. This handler prompts the email API service you configured to send the email.

Test locally

You can use the Netlify CLI to trigger an email during the development process to test out your code before deploying.

  1. Launch Netlify Dev to start a development environment that can run your code for triggering the email:
netlify dev
  1. While the Netlify Dev environment is running, trigger a test of the email by visiting the URL below, replacing YOUR_EMAIL_TEMPLATE_SUBDIRECTORY with a valid value from your project.

http://localhost:8888/.netlify/functions/emails/YOUR_EMAIL_TEMPLATE_SUBDIRECTORY

For example, for a subscribed email stored in your project at /emails/subscribed/index.html, visit http://localhost:8888/.netlify/functions/emails/subscribed to trigger the email.

The email will be sent using the email API service you configured.

Now it’s your turn!

You now have all the knowledge you need to start spinning up new email services left and right! If you’re interested in digging into the docs, we’ve got you covered.

Keep reading

Recent posts

Book cover with the title Deliver web project 10 times faster with Jamstack enterprise

Deliver web projects 10× faster

Get the whitepaper