Serverless Example: Sending Transactional Emails via SendGrid and Google Cloud Functions

Serverless is a trend in software and it could be useful in some cases. I prepared a simple example that demonstrates how to send a simple transactional email via SendGrid using Google Cloud Functions. The main idea is to split the complex function into simple sub-functions that could be managed independently.

For example, you have a simple newsletter subscription sub-system, consists of the subscription form, some kind of confirmation or/and welcome email, and some kind of function that should send this email to the end user. I want to keep the process of editing the email content for subscription form styles as simple as possible.

Suppose you have a transaction email template in SendGrid, find the ID, it should looks like dvv7767d-4180-4131-8460-4cb9283213df and keep it, we will use this later.

SendGrid Template

For this example, I will use the Serverless Framework to make things done fast.

# Install serverless globally
npm install serverless -g

# Login to your Serverless account
serverless login

# Create a serverless function
serverless create --template hello-world

#Deploy to cloud provider
serverless deploy

Suppose you already have a Google account and you already use Google Cloud Platform. To start, you need to create a new project and follow the installation instructions and also how to get and set up the credentials. Be sure that you have enabled the Cloud Functions API and the Google Cloud Deployment Manager V2 API.

To move forward, grab my example code and let’s go through the main things.

I have using the SendGrid Node.js API Library to send the transactional email and CORS package for providing an Access-Control-Allow-Origin header for the response. Replace SENDGRID_API_KEY, SENDGRID_TEMPLATE_ID, and [email protected] with your own.

'use strict';

const sendgrid = require('@sendgrid/mail');
const cors = require('cors')();

sendgrid.setApiKey('SENDGRID_API_KEY');

exports.http = (request, response) => {

  cors(request, response, () => {

    ...

    const msg = {
      to: request.body.email,
      from: '[email protected]',
      templateId: 'SENDGRID_TEMPLATE_ID',
      substitutionWrappers: ['{{', '}}'],
      substitutions: {
        name: name
      },
    };

    sendgrid
    .send(msg)
    .then(() => {
      response.status(200).json({ success: 'Email sent.' });
    })
    .catch(error => {
      response.status(500).json({ error: error.toString() });
    });
  })
};

Try the simple demo build with Vue and has been hosted within the GitLab pages and where I have added some additional things like reCAPTCHA to avoid the spam. This is the almost real-world case, that doesn’t require any server-side installation.

Serverless Demo

Feel free to ask any questions, I could share the full demo code on the request.