Lots of people lately are organising their very own newsletters. You’ve acquired the present massive names like Substack and MailChimp, corporations like Twitter are stepping into it with Revue, and even Fb is stepping into the e-newsletter enterprise. Some of us try to carry it nearer to dwelling with a self-managed WordPress resolution through MailPoet.
Let’s speak about one other chance: amassing your individual e mail subscribers the nice ol’ usual method: a <type> that submits to an API and places them into knowledge storage.
The primary hurdle in organising a e-newsletter is a mechanism to gather emails. Most apps that show you how to with constructing and sending newsletters will provide some sort of copy-and-paste signup type instance, however most of those choices are paid and we’re searching for one thing that’s free and utterly hosted by us.
Nothing is handier than organising our personal system which we will management. On this tutorial, we are going to arrange our personal system to gather emails for our newsletters based mostly on the Jamstack structure. We are going to implement an HTML type to gather emails for our e-newsletter, course of these emails with Netlify Capabilities, and save them to a Notion database with the Notion API.
However earlier than we start…
We’d like the next issues:
A Netlify accountA Notion accountA Mailgun account. In case you don’t have one, click on right here to create a free account.
All of those providers are free (with limits). And so far as Mailgun goes, we may actually use any e mail service supplier that gives an API.
Get all the code used on this tutorial over at GitHub.
First off, Notion
What’s Notion, you ask? Let’s allow them to describe it:
Notion is a single house the place you possibly can suppose, write, and plan. Seize ideas, handle initiatives, and even run a complete firm — and do it precisely the best way you need.
In different phrases, Notion is form of like a database however with a pleasant visible interface. And every row within the database will get its personal “web page” the place writing content material will not be in contrast to writing a weblog submit within the WordPress block editor.
And people databases will be visualized in quite a lot of methods, from a easy spreadsheet to a Trello-like board, or a gallery, or a calendar, or a timeline, or a… you get the image.
We’re utilizing Notion as a result of we will arrange tables that retailer our type responses, making it principally an information retailer. Notion additionally simply so occurred to just lately launch a full API for public use. We are able to make the most of that API and work together with it utilizing…
Netlify Capabilities
Netlify Capabilities are serverless API endpoints supplied by, after all, Netlify’s internet hosting platform. We are able to write them in JavaScript or Go.
We may use Netlify varieties right here to gather type submissions. In truth, Matthew Ström already shared how that works. However on a free plan, we will solely obtain 100 submissions monthly. So, that’s why we’re utilizing Netlify Capabilities — they are often invoked 125,000 occasions a month, which means we will gather a quarter-million emails each month with out paying a single penny.
Let’s arrange the Notion database
The very first thing we have to do is create a database in Notion. All that takes is creating a brand new web page, then inserting a full-page desk block by typing /desk.
Typing a command in Notion, like /desk, opens up a contextual menu to insert a block on a web page.
Let’s give our database a reputation: E-newsletter Emails.
We need to preserve issues fairly easy, so all we’re amassing is an e mail tackle when somebody submits the shape. So, actually, all we want is a column within the desk referred to as E mail.
However Notion is a bit of smarter than that and contains superior properties that present further data. A type of is a “Created time” property which, true to its title, prints a timestamp for when a brand new submission is created.
Now, when a brand new “E mail” entry is added to the desk, the date it was added is displayed as nicely. That may be good for different issues, like calculating how lengthy somebody has been a subscriber.
We additionally want a Notion API Token
As a way to work together with our Notion database, we have to create a Notion integration and get an API token. New integrations are made, not in your notion account, however on the Notion web site if you’re logged into your account. We’ll give this integration a reputation that’s equally inventive because the Notion desk: E-newsletter Signups.
Create a brand new Notion integration and affiliate it with the workspace the place the E-newsletter Emails desk lives.
As soon as the mixing has been created, we will seize the Inside Integration Token (API Token). Maintain onto it as a result of we’ll use it in only a bit.
As soon as the mixing has been created, Notion gives a secret API token that’s used to authenticate connections.
By default, Notion Integrations are literally unable to entry Notion pages or databases. We have to explicitly share the precise web page or database with our integration to ensure that the mixing to correctly learn and use data within the desk. Click on on the Share hyperlink on the top-right nook of the Notion database, use the selector to search out the mixing by its title, then click on Invite.
Subsequent is Netlify
Our database is all set to start out receiving type submissions from Notion’s API. Now’s the time to create a type and a serverless operate for dealing with the shape submissions.
Since we’re organising our web site on Netlify, let’s set up the Netlify CLI on our native machine. Open up Terminal and use this command:
npm set up netlify-cli -g
Primarily based in your style, we will authenticate to Netlify in several methods. You possibly can observe Netlify’s wonderful information as a place to begin. As soon as we now have authenticated with Netlify, the following factor we now have to do is to create a Netlify challenge. Listed below are the instructions to try this:
$ mkdir newsletter-subscription-notion-netlify-function
$ cd newsletter-subscription-notion-netlify-function
$ npm init
Comply with together with this commit within the GitHub challenge.
Let’s write a Netlify Operate
Earlier than we get into writing our Netlify operate, we have to do two issues.
First, we have to set up the [@notionhq/client](https://github.com/makenotion/notion-sdk-js) npm package deal, which is an official Notion JavaScript SDK for utilizing the Notion API.
$ npm set up @notionhq/shopper –save
Second, we have to create a .env file on the root of the challenge and add the next two atmosphere variables:
NOTION_API_TOKEN=<your Notion API token>
NOTION_DATABASE_ID=<your Notion database>
The database ID will be present in its URL. A typical Notion web page has a URL like https://www.notion.so/{workspace_name}/{database_id}?v={view_id} the place {database_id} corresponds to the ID.
We’re writing our Netlify features within the features listing. So, we have to create a netlify.toml file on the root of the challenge to inform Netlify that our features have to be constructed from this listing.
[build] features = “features”Now, let’s create a features listing on the root of the challenge. Within the features listing, we have to create an index.js file and add the next code. This operate is offered as an API endpoint at /.netlify/features/index.
const { Consumer, LogLevel } = require(‘@notionhq/shopper’);
const { NOTION_API_TOKEN, NOTION_DATABASE_ID } = course of.env;
async operate addEmail(e mail) {
// Initialize Notion shopper
const notion = new Consumer({
auth: NOTION_API_TOKEN,
logLevel: LogLevel.DEBUG,
});
await notion.pages.create({
father or mother: {
database_id: NOTION_DATABASE_ID,
},
properties: {
E mail: {
title: [
{
text: {
content: email,
},
},
],
},
},
});
}
operate validateEmail(e mail) {
const re =
/^(([^<>()[].,;:s@"]+(.[^<>()[].,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
return re.take a look at(String(e mail).toLowerCase());
}
module.exports.handler = async operate (occasion, context) {
// Examine the request methodology
if (occasion.httpMethod != ‘POST’) {
return { statusCode: 405, physique: ‘Methodology not allowed’ };
}
// Get the physique
strive {
var physique = JSON.parse(occasion.physique);
} catch (err) {
return {
statusCode: 400,
physique: err.toString(),
};
return;
}
// Validate the e-mail
const { e mail } = physique;
if (!validateEmail(e mail)) {
return { statusCode: 400, physique: ‘E mail will not be legitimate’ };
}
// Retailer e mail in Notion
await addEmail(e mail);
return { statusCode: 200, physique: ‘okay’ };
};
Let’s break this down, block by block.
The addEmail operate is used so as to add the e-mail to our Notion database. It takes an e mail parameter which is a string.
We create a brand new shopper for authenticating with the Notion API by offering our NOTION_API_TOKEN. We now have additionally set the log degree parameter to get data associated to the execution of instructions whereas we’re creating our challenge, which we will take away as soon as we’re able to deploy the challenge to manufacturing.
In a Notion database, every entry is called a web page. So, we use the notion.pages.create methodology to create a brand new entry in our Notion database. The module.exports.handler operate is utilized by Netlify features that deal with the requests made to it.
The very first thing we examine is the request methodology. If the request methodology is one thing aside from POST, we ship again a 405 – Methodology not allowed response.
Then we parse the payload (occasion.physique) object despatched by the entrance finish. If we’re unable to parse the payload object, we ship again a 400 – Dangerous request response.
As soon as we now have parsed the request payload, we examine for the presence of an e mail tackle. We use the validateEmail operate to examine the validity of the e-mail. If the e-mail is invalid, we ship again a 400 – Dangerous request response with a customized message saying the E mail will not be legitimate.
After we now have accomplished all of the checks, we name the addEmail operate to retailer the e-mail in our Notion database and ship again a 200 – Success response that every part went efficiently.
Comply with together with the code within the GitHub challenge with commit ed607db.
Now for a fundamental HTML type
Our serverless back-end is prepared and the final step is to create a type to gather e mail submissions for our e-newsletter.
Let’s create an index.html file on the root of the challenge and add the next HTML code to it. Word that the markup and courses are pulled from Bootstrap 5.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Suitable” content material=”IE=edge”>
<meta title=”viewport” content material=”width=device-width, initial-scale=1.0″>
<title>Notion + Netlify Capabilities E-newsletter</title>
<hyperlink href=”<https://cdn.jsdelivr.web/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css>” rel=”stylesheet” integrity=”sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We” crossorigin=”nameless”>
</head>
<physique>
<div class=”container py-5″>
<p>
Get every day suggestions associated to Jamstack in your inbox.
</p>
<div id=”type” class=”row”>
<div class=”col-sm-8″>
<enter title=”e mail” sort=”e mail” class=”form-control” placeholder=”Your e mail” autocomplete=”off”>
<div id=”feedback-box” class=”invalid-feedback”>
Please enter a legitimate e mail
</div>
</div>
<div class=”col-sm-4″>
<button class=”btn btn-primary w-100″ sort=”button” onclick=”registerUser()”>Submit type</button>
</div>
</div>
<div id=”success-box” class=”alert alert-success d-none”>
Thanks for subscribing to our e-newsletter.
</div>
<div id=”error-box” class=”alert alert-danger d-none”>
There was some drawback including your e mail.
</div>
</div>
</physique>
<script>
</script>
</html>
We now have an enter area for amassing consumer emails. We now have a button that, when clicked, calls the registerUser operate. We now have two alerts which are proven, one for a profitable submission and one for an unsuccessful submission.
Since we now have put in Netlify CLI, we will use the netlify dev command to run our web site on the localhost server:
$ netlify dev
As soon as the server is up and working, we will go to localhost:8888 and see our webpage with the shape.
Subsequent, we have to write some JavaScript that validates the e-mail and sends an HTTP request to the Netlify operate. Let’s add the next code within the <script> tag within the index.html file:
operate validateEmail(e mail) {
const re =
/^(([^<>()[].,;:s@”]+(.[^<>()[].,;:s@”]+)*)|(“.+”))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
return re.take a look at(String(e mail).toLowerCase());
}
async operate registerUser() {
const type = doc.getElementById(‘type’);
const successBox = doc.getElementById(‘success-box’);
const errorBox = doc.getElementById(‘error-box’);
const feedbackBox = doc.getElementById(‘feedback-box’);
const e mail = doc.getElementsByName(‘e mail’)[0].worth;
if (!validateEmail(e mail)) {
feedbackBox.classList.add(‘d-block’);
return;
}
const headers = new Headers();
headers.append(‘Content material-Sort’, ‘software/json’);
const choices = {
methodology: ‘POST’,
headers,
physique: JSON.stringify({e mail}),
};
const response = await fetch(‘/.netlify/features/index’, choices);
if (response.okay) {
type.classList.add(‘d-none’);
successBox.classList.take away(‘d-none’);
}
else {
type.classList.add(‘d-none’);
errorBox.classList.take away(‘d-none’);
}
}
Within the registerUser operate, we examine the validity of the e-mail enter utilizing a RegEx operate (validateEmail). If the e-mail is invalid, we immediate the consumer to strive once more. As soon as we now have validated the e-mail, we name the fetch methodology to ship a POST request to our Netlify operate which is offered at /.netlify/features/index with a payload object containing the consumer’s e mail.
Primarily based on the response, we present a hit alert to the consumer in any other case we present an error alert.
Comply with together with the code within the GitHub challenge with commit cd9791b.
Getting the Mailgun credentials
Getting emails in our database is sweet, however not sufficient, as a result of we don’t know the way we’re going to use them. So, the ultimate step is to ship a affirmation e mail to a subscriber after they enroll.
We’re not going to ship a message instantly after a consumer indicators up. As an alternative, we are going to arrange a way to fetch the e-mail signups within the final half-hour, then ship the e-mail. Including a delay to the auto-generated e mail makes the welcome message really feel a bit extra private, I believe.
We’re utilizing Mailgun to ship, however once more, we may actually use any e mail service supplier with an API. Let’s go to the Mailgun dashboard and, from the sidebar, go to the Settings → API Keys display.
We wish the “Non-public API key.”
Let’s copy the Non-public API key and add it to the .env file as:
MAILGUN_API_KEY=<your Mailgun api key>
Each e mail wants to return from a sending tackle, so yet another factor we want is the Mailgun area from which the emails are despatched. To get our Mailgun area, we have to go to the Sending → Domains display.
Mailgun gives a sandbox area for testing.
Let’s copy our Mailgun sandbox area and add it to the .env file as:
MAILGUN_DOMAIN=<your Mailgun area>
Sending a confrimation e mail
Earlier than we get into writing our Netlify operate for sending an e mail affirmation, we have to set up the [mailgun-js](https://github.com/mailgun/mailgun-js) npm package deal, which is an official Mailgun JavaScript SDK for utilizing the Mailgun API:
$ npm set up mailgun-js –save
We’re utilizing the /.netlify/features/index endpoint for sending welcome emails. So, within the features listing, let’s create a brand new a welcome.js file and add the next code:
const { Consumer, LogLevel } = require(‘@notionhq/shopper’);
const mailgun = require(‘mailgun-js’);
const {
NOTION_API_TOKEN,
NOTION_DATABASE_ID,
MAILGUN_API_KEY,
MAILGUN_DOMAIN,
} = course of.env;
async operate fetchNewSignups() {
// Initialize notion shopper
const notion = new Consumer({
auth: NOTION_API_TOKEN,
logLevel: LogLevel.DEBUG,
});
// Create a datetime that’s 30 minutes sooner than the present time
let fetchAfterDate = new Date();
fetchAfterDate.setMinutes(fetchAfterDate.getMinutes() – 30);
// Question the database
// and fetch solely entries created within the final 30 minutes
const response = await notion.databases.question({
database_id: NOTION_DATABASE_ID,
filter: {
or: [
{
property: ‘Added On’,
date: {
after: fetchAfterDate,
},
},
],
},
});
const emails = response.outcomes.map((entry) => entry.properties.E mail.title[0].plain_text);
return emails;
}
async operate sendWelcomeEmail(to) {
const mg = mailgun({ apiKey: MAILGUN_API_KEY, area: MAILGUN_DOMAIN });
const knowledge = {
from: `Ravgeet Dhillon <postmaster@${MAILGUN_DOMAIN}>`,
to: to,
topic: ‘Thanks for subscribing’,
textual content: “Thanks for subscribing to my e-newsletter. I will be sending every day suggestions associated to JavScript.”,
};
await mg.messages().ship(knowledge);
}
module.exports.handler = async operate (occasion, context) {
// Examine the request methodology
if (occasion.httpMethod != ‘POST’) {
return { statusCode: 405, physique: ‘Methodology not allowed’ };
}
const emails = await fetchNewSignups();
emails.forEach(async (e mail) => {
await sendWelcomeEmail(e mail);
});
return { statusCode: 200, physique: ‘okay’ };
};
The above code has two primary features which we have to be understood. First, we now have a fetchNewSignups operate. We use the Notion SDK shopper to fetch the entries in our Notion database. We now have used a filter to fetch solely these emails which have been added within the final half-hour. As soon as we get a response from the Notion API, we loop over the response and map the e-mail into an emails array.
Second, we now have a sendWelcomeEmail operate. This operate is used to ship an e mail to the brand new subscriber through Mailgun API.
To carry every part collectively, we loop over the brand new emails within the module.exports.handler operate and ship a welcome e mail to every new e mail.
This operate is offered at localhost:8888/.netlify/features/welcome.
Comply with together with the code within the GitHub challenge with commit b802f93.
Let’s take a look at this out!
Now that our challenge is prepared, the very first thing we have to do is to check the shape and see whether or not the e-mail is saved in our Notion database. Let’s go to localhost:8888 and enter a legitimate e mail tackle.
Good! We acquired the success message. Now let’s head over to our Notion database to see if the e-mail tackle was captured.
Superior, it’s there! We are able to additionally see that the Added On area has additionally been auto-filled by Notion, which is strictly what we wish.
Subsequent, let’s ship a POST request to localhost:8888/.netlify/features/welcome from Postman and examine our inbox for the subscription affirmation message.
Woah! We now have obtained the welcome e mail for subscribing to the e-newsletter.
Not seeing the e-mail in your inbox? Be certain that to examine your spam folder.
What’s subsequent?
The subsequent step from right here could be to arrange a script that runs each half-hour and calls the welcome endpoint. As of now, Netlify doesn’t present any method to run CRON jobs. So, we will arrange GitHub Actions to deal with it.
Additionally, we will safe the welcome endpoint utilizing safety mechanisms like a easy password or a JWT token. This can stop anybody on the Web from calling the welcome endpoint and sending tons of spam to our subscribers.
So, there we now have it! We efficiently carried out a Jamstack method to gather emails for a e-newsletter. The most important benefit of doing one thing like that is that we will study loads about completely different applied sciences directly. We wired collectively providers and APIs that gather e mail addresses, validate submissions, submit to databases, and even ship emails. It’s fairly cool that we will accomplish that a lot with comparatively so little.
I hope you loved studying and studying one thing from this text as a lot as I loved writing it for you. Let me know within the feedback the way you used this methodology to your personal profit. Completely happy coding!
The submit Accumulating E mail Signups With the Notion API appeared first on CSS-Tips. You possibly can assist CSS-Tips by being an MVP Supporter.
Subscribe to MarketingSolution.
Receive web development discounts & web design tutorials.
Now! Lets GROW Together!