Sending Emails with SendGrid

You can use SendGrid to power your emails on Google 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

Google App Engine customers can send 12,000 emails every month for free. Create a SendGrid account to claim the free emails and to select higher volume plans. Note that Google will be 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.

Setup

To use SendGrid to send an email:

  1. Create a new project in the console or use an existing app. For further instructions on how to create a project, see "Hello, World!" for Node.js on App Engine.

  2. Create a SendGrid account.

  3. Add your SendGrid settings to the environment variables section in app.yaml. For example, for the sample code below you would add:

    env_variables:
      SENDGRID_API_KEY: <your-sendgrid-api-key>
      SENDGRID_SENDER: <your-sendgrid-sender>
  4. Add the sendgrid Node.js library to your application's package.json. For example: npm install --save sendgrid

Example

You can create a SendGrid instance and use it to send mail. In the following sample code, the /send/email handler in app.js 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 when running on GAE,
// 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
    });
    return;
  });
});

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.

Testing and Deploying

Before you run your app locally, set the environment variables on your local machine using the command line. For example, for the sample code above:

export SENDGRID_API_KEY= your-sendgrid-api-key
export SENDGRID_SENDER= your-sendgrid-sender-email-address

You can run the application locally to test the callbacks and SMS transmission. For example:

npm start

After you test your application, deploy your project to App Engine:

gcloud app deploy

Getting real-time information

In addition to sending email, SendGrid can help you receive email or make sense of the email you’ve already sent. The two real-time webhook solutions can greatly enhance the role email plays in your application.

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 small bit of descriptive JSON to your Google App Engine app. You can react to the event or store the data for future use.

You can use this event data in many different ways, such as integrating email stats into internal dashboards or responding immediately to unsubscribes and spam reports. Advanced users of the Event API raise the engagement of their emails by sending only to those who have clicked or opened within the last few months.

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 excels at sending email, but it can also receive email. The Inbound Parse API can be used for powerful, interactive applications. For example, automate support tickets from customer emails, or collect data via short emails employees dispatch from the road. NudgeMail's reminder application is even built entirely on the Parse API.

Like the Event API, 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. Due to intricacies in the way DNS works for email, you need to assign all incoming mail to the domain or subdomain you use for the Parse API.

Emails are sent to your application structured as JSON, with sender, recipients, subject and body as different fields. You can even accept attachments, within SendGrid’s limit of messages up to 20 MB in size.

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

Send feedback about...

App Engine flexible environment for Node.js docs