How to Send Email Using SendGrid from Node.js

This guide demonstrates how to perform common programming tasks with the SendGrid email service on Azure. The samples are written using the Node.js API. The scenarios covered include constructing email, sending email, adding attachments, using filters, and updating properties. For more information on SendGrid and sending email, see the Next Steps section.

What is the SendGrid Email Service?

SendGrid is a cloud-based email service that provides reliable transactional email delivery, scalability, and real-time analytics along with flexible APIs that make custom integration easy. Common SendGrid usage scenarios include:

  • Automatically sending receipts to customers
  • Administering distribution lists for sending customers monthly e-fliers and special offers
  • Collecting real-time metrics for things like blocked e-mail, and customer responsiveness
  • Generating reports to help identify trends
  • Forwarding customer inquiries
  • Email notifications from your application

For more information, see https://sendgrid.com.

Create a SendGrid Account

Azure customers can unlock 25,000 free emails each month. These 25,000 free monthly emails will give you access to advanced reporting and analytics and all APIs (Web, SMTP, Event, Parse and more). For information about additional services provided by SendGrid, visit the SendGrid Solutions page.

To sign up for a SendGrid account

  1. Log in to the Azure Management Portal.
  2. In the menu on the left, click New.

    command-bar-new

  3. Click Add-ons and then SendGrid Email Delivery.

    sendgrid-store

  4. Complete the signup form and select Create.

    sendgrid-create

  5. Enter a Name to identify your SendGrid service in your Azure settings. Names must be between 1 and 100 characters in length and contain only alphanumeric characters, dashes, dots, and underscores. The name must be unique in your list of subscribed Azure Store Items.
  6. Enter and confirm your Password.
  7. Choose your Subscription.
  8. Create a new Resource group or use an existing one.
  9. In the Pricing tier section select the SendGrid plan you want to sign up for.

    sendgrid-pricing

  10. Enter a Promotion Code if you have one.
  11. Enter your Contact Information.
  12. Review and accept the Legal terms.
  13. After confirming your purchase you will see a Deployment Succeeded pop-up and you will see your account listed in the All resources section.

    all-resources

    After you have completed your purchase and clicked the Manage button to initiate the email verification process, you will receive an email from SendGrid asking you to verify your account. If you do not receive this email, or have problems verifying your account, please see this FAQ.

    manage

    You can only send up to 100 emails/day until you have verified your account.

    To modify your subscription plan or see the SendGrid contact settings, click the name of your SendGrid service to open the SendGrid Marketplace dashboard.

    settings

    To send an email using SendGrid, you must supply your API Key.

To find your SendGrid API Key

  1. Click Manage.

    manage

  2. In your SendGrid dashboard, select Settings and then API Keys in the menu on the left.

    api-keys

  3. Click the Create API Key dropdown and select General API Key.

    general-api-key

  4. At a minimum, provide the Name of this key and provide full access to Mail Send and select Save.

    access

  5. Your API will be displayed at this point one time. Please be sure to store it safely.

To find your SendGrid credentials

  1. Click the key icon to find your Username.

    key

  2. The password is the one you chose at setup. You can select Change password or Reset password to make any changes.

To manage your email deliverability settings, click the Manage button. This will redirect to your SendGrid dashboard.

![manage][manage]

For more information on sending email through SendGrid, visit the [Email API Overview][Email API Overview].

Reference the SendGrid Node.js Module

The SendGrid module for Node.js can be installed through the node package manager (npm) by using the following command:

npm install sendgrid

After installation, you can require the module in your application by using the following code:

var sendgrid = require('sendgrid')(sendgrid_username, sendgrid_password);

The SendGrid module exports the SendGrid and Email functions. SendGrid is responsible for sending email through Web API, while Email encapsulates an email message.

How to: Create an Email

Creating an email message using the SendGrid module involves first creating an email message using the Email function, and then sending it using the SendGrid function. The following is an example of creating a new message using the Email function:

var email = new sendgrid.Email({
    to: 'john@contoso.com',
    from: 'anna@contoso.com',
    subject: 'test mail',
    text: 'This is a sample email message.'
});

You can also specify an HTML message for clients that support it by setting the html property. For example:

html: This is a sample <b>HTML<b> email message.

Setting both the text and html properties provides graceful fallback to text content for clients that cannot support HTML messages.

For more information on all properties supported by the Email function, see sendgrid-nodejs.

How to: Send an Email

After creating an email message using the Email function, you can send it using the Web API provided by SendGrid.

Web API

sendgrid.send(email, function(err, json){
    if(err) { return console.error(err); }
    console.log(json);
});
Note

While the above examples show passing in an email object and callback function, you can also directly invoke the send function by directly specifying email properties. For example:

sendgrid.send({
to: 'john@contoso.com',
from: 'anna@contoso.com',
subject: 'test mail',
text: 'This is a sample email message.'
});

How to: Add an Attachment

Attachments can be added to a message by specifying the file name(s) and path(s) in the files property. The following example demonstrates sending an attachment:

sendgrid.send({
    to: 'john@contoso.com',
    from: 'anna@contoso.com',
    subject: 'test mail',
    text: 'This is a sample email message.',
    files: [
        {
            filename:     '',           // required only if file.content is used.
            contentType:  '',           // optional
            cid:          '',           // optional, used to specify cid for inline content
            path:         '',           //
            url:          '',           // == One of these three options is required
            content:      ('' | Buffer) //
        }
    ],
});
Note

When using the files property, the file must be accessible through fs.readFile. If the file you wish to attach is hosted in Azure Storage, such as in a Blob container, you must first copy the file to local storage or to an Azure drive before it can be sent as an attachment using the files property.

How to: Use Filters to Enable Footers and Tracking

SendGrid provides additional email functionality through the use of filters. These are settings that can be added to an email message to enable specific functionality such as enabling click tracking, Google analytics, subscription tracking, and so on. For a full list of filters, see Filter Settings.

Filters can be applied to a message by using the filters property. Each filter is specified by a hash containing filter-specific settings. The following examples demonstrate the footer and click tracking filters:

var email = new sendgrid.Email({
    to: 'john@contoso.com',
    from: 'anna@contoso.com',
    subject: 'test mail',
    text: 'This is a sample email message.'
});

email.setFilters({
    'footer': {
        'settings': {
            'enable': 1,
            'text/plain': 'This is a text footer.'
        }
    }
});

sendgrid.send(email);

Click Tracking

var email = new sendgrid.Email({
    to: 'john@contoso.com',
    from: 'anna@contoso.com',
    subject: 'test mail',
    text: 'This is a sample email message.'
});

email.setFilters({
    'clicktrack': {
        'settings': {
            'enable': 1
        }
    }
});

sendgrid.send(email);

How to: Update Email Properties

Some email properties can be overwritten using set*Property* or appended using add*Property*. For example, you can add additional recipients by using

email.addTo('jeff@contoso.com');

or set a filter by using

email.addFilter('footer', 'enable', 1);
email.addFilter('footer', 'text/html', '<strong>boo</strong>');

For more information, see sendgrid-nodejs.

How to: Use Additional SendGrid Services

SendGrid offers web-based APIs that you can use to leverage additional SendGrid functionality from your Azure application. For full details, see the SendGrid API documentation.

Next Steps

Now that you've learned the basics of the SendGrid Email service, follow these links to learn more.