Sending Emails with SendGrid

You can use SendGrid to power your emails on App Engine. SendGrid can improve your deliverability and provide transparency into what actually happens to those emails your app sends. You can see statistics on opens, clicks, unsubscribes, spam reports and more with the SendGrid interface or its API.

Pricing

App Engine customers can send 12,000 emails every month for free by signing up for the SendGrid Email API plan through the Google Cloud Platform Console. Note that Google is compensated for customers who sign up for a paid account.

SendGrid libraries

You can send email with SendGrid through an SMTP relay or using a Web API.

To integrate SendGrid with your App Engine project, use the SendGrid client libraries.

Before you begin

To use SendGrid to send an email:

  1. Sign up for the SendGrid Email API plan
  2. Take note of the Sendgrid API key.
  3. Select or create a new GCP project in the Google Cloud Platform Console and then ensure an App Engine application exists and billing is enabled:

    Go to App Engine

    The Dashboard opens if an App Engine application already exists in your project and billing is enabled. Otherwise, follow the prompts for choosing a region and enabling billing.
  4. Add your SendGrid API key to the environment variables section in app.standard.yaml.
  5. Add the SendGrid Node.js client library to your application's package.json. For example:
    npm install --save sendgrid

Sending mail

You can create a SendGrid instance and use it to send mail.

The following sample code shows how to send an email and specifies some error handling:

'use strict';

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');

// The following environment variables are set by app.yaml (app.flexible.yaml or
// app.standard.yaml) when running on Google App Engine,
// but will need to be manually set when running locally.
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.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
    });
  });
});

if (module === require.main) {
  const PORT = process.env.PORT || 8080;
  app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
    console.log('Press Ctrl+C to quit.');
  });
}

module.exports = app;

Add your own account details, and then edit the email address and other message content.

For more email settings and examples, see the SendGrid-Node.js library.

Getting real-time information

In addition to sending email, SendGrid can receive email or make sense of the email you’ve already sent using webhooks.

Event API

Once you start sending email from your application, you can view statistics collected by SendGrid to assess your email program. You can use the Event API to see this data. For example, whenever a recipient opens or clicks an email, SendGrid can send a descriptive JSON to your Google App Engine app that can react to the event or store the data for future use.

The Event API documentation shows how to set up the webhook, outlines the nine event types and shows the fields included in event callbacks.

Inbound Parse API

SendGrid can receive email. The Inbound Parse API can be used for interactive applications, such as automating support tickets.

The Parse API is a webhook that sends data to your application when something new is available. In this case, the webhook is called whenever a new email arrives at the domain you've associated with incoming email.

Emails are sent to the application structured as JSON, with sender, recipients, subject, and body as different fields. Attachments of up to 20MB are allowed.

The Parse API documentation has more details, including additional fields sent with every email, as well as instructions for DNS setup and usage.

Was this page helpful? Let us know how we did:

Send feedback about...

App Engine standard environment for Node.js docs