Sending emails using Netlify Functions and Sendgrid

12 June 2020

The below guide was heavily inspired by the team behind They deserve all the credit.

If you want to learn more about serverless functions provided by Netlify I recommend Netlify Lambda Functions Tutorial and AWS (?) made simple: What is a Netlify function? blog post.

Create Sendgrid account and get the API key

Remember that besides API key a user also has to do "Sender Authentication" and if she/he chooses "Single Sender Verification" then the from and to emails from your snippet have to be the same. For more information please refer to: How to set up domain authentication and Sender Identity.

Create a serverless function

Create a folder for functions in your root directory and put a .js file inside

touch /functions/sendmail/sendmail.js

Let's include subfolders in case later we'll be using more than one serverless function.

Let's also use the fact that Netlify can install packages during its build process and in the sendmail folder initiate package.json:

npm init -y

This will setup package.json just for the /sendmail and will enable us to install packages in a subfolder:

npm install --save @sendgrid/mail

Now the sendmail.js:

const client = require('@sendgrid/mail');
const {
} = process.env;

exports.handler = async function (event, context, callback) {
  const { message, senderEmail, senderName } = JSON.parse(event.body);

  const data = {
    subject: `New message from ${senderName} (${senderEmail})`,
    html: message,

  try {
    await client.send(data);
    return {
      statusCode: 200,
      body: 'Message sent',
  } catch (err) {
    return {
      statusCode: err.code,
      body: JSON.stringify({ msg: err.message }),

Configure Netlify boilerplate

Install Netlify CLI

npm i -g netlify-cli

Next in project root run:

netlify init

In project root create netflify.toml:

  publish = "dist"
  functions = './functions/'

Then, again in project root install:

npm i netlify-lambda

And add postinstall script in your root's package.json

  "scripts": {
    "postinstall": "netlify-lambda install",

Lastly, run:

npm i

Set up environmental variables in Netlify

In your project's panel on Netlify, in the Settings section fill in your environmental variables.

And you're all set to send emails from your contact form!

P.S. To locally test that function run:

netlify dev

This will spin up the project connected with Netlify including your functions and API keys.