> Contact

Please answer the questions below to send me a message.

(1 / 3) Reset | Exit

> Hello there, what is your name?

> Blog

Send email using Netlify functions and Sendgrid API

If you have ever built a static site then I'm sure you would've heard of Netlify, the fantastic (and free) static hosting company. Netlify offers everything you need to get your static site up and running quickly, their free plan offers 100GB of bandwidth, custom domain, HTTPS, Git integration, continuous integration and much more. I'm going to explore Netlify functions in this post and how we can use them to send an email with Sendgrid.

Static sites are great, they're extremely fast and due to the fact there is no dynamic functionality in them that could be breached, they are more secure. However, most websites are going to need some dynamic functionality, typically this can be added to your static site using AJAX and connecting to an API. This approach would mean you'd have to have a server to host your API and configure it to be accessible and secure, the exact type of issues that static sites are here to alleviate.

Luckily Netlify offers Netlify Functions, these are small Node.js functions that run on Netlify's server that are accessible by your application. See below how we can create a function to send an email using Sendgrid API.

1. Create a SendGrid Account and Get an API Key

If you have not got SendGrid account already, then head to their website and create an account, it is free for up to 100 emails a day but they offer other pricing tiers if that does not meet your requirements. Once you've created an account and logged in, you'll need to create a SendGrid API key, this should be the first screen you are presented with when logging in if you aren't then you can find API keys in the menu under Settings. Once you've got your API key make sure you keep it safe for use later, be sure to save it as you cannot view this again.

2. Create a Netlify Function

By default, Netlify looks in a folder named functions in the root of your repository for any javascript files, so go ahead and create a folder called functions and create a file named sendgrid.js inside it. First of all, we are going to want to install SendGrid mail package.

NPM: npm install --save @sendgrid/mail

Yarn: yarn add @sendgrid/mail

Once that package is installed then go ahead and open the sendgrid.js file you created in the functions folder and add the following code to it.

./functions/sendgrid.js

const client = require("@sendgrid/mail")

function sendEmail(client, message, senderEmail, senderName) {
  return new Promise((fulfill, reject) => {
    const data = {
      from: {
        email: senderEmail,
        name: senderName
      },
      subject: 'Netlify Function - Sendgrid Email',
      to: 'your.email@here.com',
      html: `Hey, you\'ve sent an email from Netlify Functions<br/>Message: ${message}`
    }

    client
      .send(data)
      .then(([response, body]) => {
        fulfill(response)
      })
      .catch(error => reject(error))
  })
}

exports.handler = function(event, context, callback) {
  const {
    SENDGRID_API_KEY,
    SENDGRID_SENDER_EMAIL,
    SENDGRID_SENDER_NAME
  } = process.env

  const body = JSON.parse(event.body)
  const message = body.message

  client.setApiKey(SENDGRID_API_KEY)

  sendEmail(
    client,
    message,
    SENDGRID_SENDER_EMAIL,
    SENDGRID_SENDER_NAME
  )
  .then(response => callback(null, { statusCode: response.statusCode }))
  .catch(err => callback(err, null))
}

Okay this is fairly straight forward we first require the SendGrid mail package, then we have an exports.handler which calls a function named sendEmail. This code should be somewhat typical javascript you will be familiar with, the only thing unique to Netlify functions is the use of process.env:

const {
    SENDGRID_API_KEY,
    SENDGRID_SENDER_EMAIL,
    SENDGRID_SENDER_NAME
  } = process.env

This is how we access Netlify's environment variables.

3. Set Up Netlify Environment Variables

Log in to your Netlify account and navigate to Settings > Build and Deploy > Environment and add new variables for SENDGRID_API_KEY, SENDGRID_SENDER_EMAIL and SENDGRID_SENDER_NAME, and give them a value (use your SendGrid API key you kept safe from earlier). Now your Netlify function should be ready to go but need to call it from your application.

4. Calling Your Netlify function

There is nothing specific when calling the Netlify function just do an AJAX request the way you normally would. The URL for the SendGrid function will be /.netlify/functions/sendgrid. My example is from a Nuxt.js App using Axios to POST to my SendGrid Netlify function. This is just a very basic example with a hardcoded message, and an alert to say if the message was sent successfully or not.

methods: {
  async submit() {
      try {
        await this.$axios.post(
          '/.netlify/functions/sendgrid',
          {
            message: 'My email message, in the real world this would probably come from form data '
          }
        )
        alert('Thank you, your message was sent successfully!')
      } catch (e) {
        console.error(e)
        alert('Error:  Your message could not be sent')
      }
    }
}

5. Upload to Netlify

I'm not going to go into setting up a website on Netlify, I'm going to assume you already have a site on Netlify and uploading this code will be as simple as committing into your master branch in your repository. Once your site builds on Netlify you should see your function listed on the Functions page in Netlify, this is where you can see logs from your function which is useful when debugging.

And that is all there is to it if you have any questions just leave a comment below and I'll try to get back to you as soon as I can.

// Comments