Sending emails with Netlify Functions

Let’s say you’ve built your first modern static website (JAMStack) and want to make it more dynamic, e.g. by sending emails with dynamic content and file attachments. But you don’t want to set up or use your server for this. We explain how to do this in this post.

What do you need?

1. Mailing service

First of all, you need a mailing service that sends your emails. You shouldn’t send emails from your email server, but use a larger service provider to avoid the risk of being classified as a spam sender, for example. To send an email, you address the service API with an API key and hand over all the data that should be contained in the email and the mailing service then sends it to the target address.

There are many services to choose from and you should choose the one that suits you best in terms of features and price. Since I enjoyed working with POSTMARK on my last project, in this post I will introduce how to use this service.

2. Netlify

Next, we need a small amount of server-side code to protect the API key on the API request. Lambda functions are ideal for this. A URL endpoint is called up and a given code is executed when it is called. Netlify supports this, so it would be a good idea to host your site on it.

Step 1: Set up the mail service

Set up POSTMARK

The first thing we do is log into Postmark and go through all the steps until we get to the dashboard and have access to the API token.

API Token

Provide the API key for Netlify

To protect the API key, the key should only be made available when executing server-side codes. In Netlify we have to assign the key to a variable under “Environment”.

API Key Environment

Step 2: write functions

How do we create a Netlify function? Very easily. In your project folder, you create a folder with the name “functions”. In this, you then create all the JavaScript files that you need. In our case, we create the file send-email.js.

/project
   ... your entire website or whatever ...
   /functions/
         send-email.js

Use Postmark Node Library

Postmark provides its Node.js library and with a look at the documentation, we discover a simple code example for testing right at the beginning.

const serverToken = "xxxx-xxxxx-xxxx-xxxxx-xxxxxx" //API Key
let postmark = require("postmark")
let client = new postmark.ServerClient(serverToken);

exports.handler = (event, context, callback) => {
client.sendEmail(
    {
        From: "from@example.com", //Deine Emailadresse
        To: "to@example.com", //Ziel Emailadresse
        Subject: "test email",
        HtmlBody: "test",
        TextBody: "test"
    }
).then(response => {
    console.log(response.To);
    console.log(response.SubmittedAt);
    console.log(response.Message);
    console.log(response.MessageID);
    console.log(response.ErrorCode);
});
}

If you are new or not familiar with the AWS Lambda functions – no problem! I’ll give you a brief overview of the individual parameters that our handler receives.

  • event is an object that contains data on the request
  • context contains the user information when using Identity for user authentication
  • callback is a function we can use to create a response

With the callback () method we can test whether our request has arrived at the Mailing Service API.

  callback(null, {
    statusCode: 200,
    body: 'I am on my way !'
  })
}

Step 3: testing

Netlify Dev

Now we have written our first Netlify function and would like to test our work. There is a small tool for this called Netlify Dev. With it, we can simulate a dev server that gives us a local URL with which we can execute and test our functions in the development environment.

After installing and running it should look something like this:

Netlify Dev

Testing the function

To call our Lambda function, we need to address it with a URL like the one below:

http://localhost:8888/.netlify/functions/send-email

If everything went well, the recipient will be happy about your first email 🙂

Testing E-Mail

Step 4: Fill the email with data

Congratulations, you have now sent your first email with the Netlify function. Unfortunately, the content is still static and boring. To breathe new life into your mail, we need to make the code more dynamic.

Let’s say you want to email several congratulations to friends and add a text file with a personal message as an attachment.

You fill in all data with a form and these are saved as an object, e.g .:

const congratulation = {
  targetEmail: "test@gmail.com", 
  reason: "Geburtstag",
  firstname: "Peter",
  message: "Alles Gute zum Geburtstag. Es freut mich das du erwachsen 
           wirst"
}

Now, this data has to be transferred to the URL of the send-mail.js function when sending. To do this, we use an HTTP request with the URL function as the target address with the form data as the payload.

axios({
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          url: '/.netlify/functions/send-email',
          data: congratulation, //payload
      })

Next, we have to fill the content of the e-mail with the data from the payload in our send-mail.js function. It is advisable to use console.log (event) when developing to display all data from the request in the terminal.

Netlify E-Mail

To add an attachment, just take a look at the Postmark Node.js documentation.

const attachment = new 
                    postmark.Models.Attachment("Glückwunschtext.txt", 
                    Buffer.from("payload.message").toString("base64"), 
                    "text");

client.sendEmail(
    {
        From: "from@example.com", //Deine Emailadresse
        To: "to@example.com", //Ziel Emailadresse
        Subject: "test email",
        HtmlBody: "test",
        TextBody: "test"
        Attachments: [attachment],
    })

The fully adapted function then looks like this in the end.

const serverToken = "xxxx-xxxxx-xxxx-xxxxx-xxxxxx" //API Key
let postmark = require("postmark")
let client = new postmark.ServerClient(serverToken);

exports.handler = (event, callback) => {
console.log(event) 
const payload = JSON.parse(event.body)

 const attachment = new 
                    postmark.Models.Attachment("Glückwunschtext.txt", 
                    Buffer.from("payload.message").toString("base64"), 
                    "text");

client.sendEmail(
    {
        From: "tung@phmu.de", //Deine Emailadresse
        To: payload.targetEmail, //Ziel Emailadresse
        Subject: payload.reason, 
        TextBody: `Liebe ${payload.firstname}, 
                  du hast eine Glückwunschemail erhalten`,
        Attachments: [attachment],
    })
} 

The content of the emails sent should then look like this:

Von: tung@phmu.de
An: test@gmail.com
Betreff: Geburtstag

Anhang: Glückwunschtext.txt

Nachricht: 
Liebe Peter, 
du hast eine Glückwunschemail erhalten             

As you can see, sending emails with Netlify Functions is not that complicated. You could now make the emails even fancier such as B. Add HTML code and … But I’ll leave that to you 😉

Leave a Reply

Your email address will not be published. Required fields are marked *