Edit on GitHub
Report issue
Page history

Author(s): @{[ username ]}  Published: {[ TutorialCtrl.tutorial.date_published | date:'mediumDate' ]}

title: Send Email with SendGrid and Node.js on Google App Engine Flexible Environment description: Learn how to send email via SendGrid from a Node.js app to Google App Engine flexible environment. author: jmdobry tags: App Engine, SendGrid, Express.js, Node.js date_published: 2016-12-13


SendGrid

SendGrid: Delivering your transactional and marketing email through one reliable platform.

– sendgrid.com

You can check out Node.js and Google Cloud Platform to get an overview of Node.js itself and learn ways to run Node.js apps on Google Cloud Platform.

Prerequisites

  1. Create a project in the Google Cloud Platform Console.
  2. Enable billing for your project.
  3. Install the Google Cloud SDK.

Prepare

  1. Sign up for a SendGrid account.

  2. Create a new API key.

  3. Initialize a package.json file with the following command:

    npm init
    
  4. Install some dependencies:

    npm install --save express body-parser pug sendgrid
    

Create

  1. Create a server.js file with the following contents:

    'use strict';
    
    const express = require('express');
    const path = require('path');
    const bodyParser = require('body-parser');
    
    const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
    const SENDGRID_SENDER = process.env.SENDGRID_SENDER;
    const Sendgrid = require('sendgrid')(SENDGRID_API_KEY);
    
    const app = express();
    
    // Setup view engine
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'pug');
    
    // Parse form data
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    
    app.get('/', (req, res) => res.render('index'));
    
    app.post('/hello', (req, res, next) => {
      const sgReq = Sendgrid.emptyRequest({
        method: 'POST',
        path: '/v3/mail/send',
        body: {
          personalizations: [{
            to: [{ email: req.body.email }],
            subject: 'Hello World!'
          }],
          from: { email: SENDGRID_SENDER },
          content: [{
            type: 'text/plain',
            value: 'Sendgrid on Google App Engine with Node.js.'
          }]
        }
      });
    
      Sendgrid.API(sgReq, (err) => {
        if (err) {
          next(err);
          return;
        }
        // Render the index route on success
        res.render('index', {
          sent: true
        });
        return;
      });
    });
    
    app.listen(process.env.PORT || 8080);
    
  2. Create a directory named views:

    mkdir views
    
  3. Create a file named index.pug inside the views directory with the following contents:

    doctype html
    html
      head
        title= title
      body
        h1 Hello World!
        p Express.js + Sendgrid on Google App Engine.
        hr
        if sent
          p Email sent!
        else
          form(name="hello", action="/hello", method="post")
            input(type="email", placeholder="Enter your email to send yourself a Hello World message", name="email", style="width: 50%; margin-right: 15px;")
            input(type="submit", value="Send")
    

Run

  1. Run the app with the following command:

    SENDGRID_SENDER=your-sendgrid-sender-email SENDGRID_API_KEY=your-sendgrid-api-key npm start
    
  2. Visit http://localhost:8080 to try sending an email.

Deploy

  1. Create an app.yaml file with the following contents:

    runtime: nodejs
    env: flex
    env_variables:
      SENDGRID_SENDER: your-sendgrid-sender-email
      SENDGRID_API_KEY: your-sendgrid-api-key
    

    The app.yaml makes the app deployable to Google App Engine Managed VMs.

  2. Run the following command to deploy your app:

    gcloud app deploy

  3. Visit http://YOUR_PROJECT_ID.appspot.com to try sending an email.

See more by @{[ username ]} and more tagged {[ tag ]}{[ $last ? '' : ', ' ]}

Submit a Tutorial

Share step-by-step guides

SUBMIT A TUTORIAL

Request a Tutorial

Ask for community help

SUBMIT A REQUEST

GCP Tutorials

Tutorials published by GCP

VIEW TUTORIALS

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies. Java is a registered trademark of Oracle and/or its affiliates.