Skip to content

SendGrid Node.js SDK — Sending Emails with the Official JavaScript Library

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about SendGrid Node.js SDK. We cover key concepts, practical examples, and best practices to help you master this topic.

The SendGrid Node.js SDK (@sendgrid/mail) provides a JavaScript interface for the SendGrid v3 API, designed for both CommonJS and ES modules, with full TypeScript support.

What You'll Learn

  • How to install and configure the SendGrid Node.js SDK
  • How to send emails with templates and attachments
  • How to handle delivery errors gracefully

Why It Matters

Node.js powers many real-time and event-driven applications that send transactional emails. The SendGrid Node.js SDK provides a promise-based API that integrates naturally with async/await patterns, making email sending non-blocking and efficient.

Real-World Use

DodaTech's Node.js notification service uses the @sendgrid/mail package to send 50,000+ emails daily. The SDK's template support allows the marketing team to update email designs without code changes, while TypeScript types ensure correct payload construction.

Installation and Setup

npm install @sendgrid/mail
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

Sending a Basic Email

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

async function sendWelcomeEmail(userEmail, userName) {
  const msg = {
    to: userEmail,
    from: 'noreply@dodatech.com',
    subject: `Welcome to DodaTech, ${userName}!`,
    html: `
      <h1>Welcome to DodaTech!</h1>
      <p>Hi ${userName},</p>
      <p>Thank you for joining. We're excited to have you.</p>
      <p>Get started:</p>
      <ul>
        <li>Complete your profile</li>
        <li>Explore the dashboard</li>
        <li>Invite your team</li>
      </ul>
    `,
    categories: ['welcome', 'onboarding']
  };

  try {
    const response = await sgMail.send(msg);
    console.log(`Email sent: ${response[0].statusCode}`);
    return true;
  } catch (error) {
    console.error('SendGrid error:', error.response?.body?.errors || error.message);
    return false;
  }
}

sendWelcomeEmail('user@example.com', 'Jane Doe');

Dynamic Templates

async function sendPasswordResetEmail(userEmail, resetLink) {
  const msg = {
    to: userEmail,
    from: 'security@dodatech.com',
    templateId: 'd-abc123def456', // Template ID from SendGrid
    dynamicTemplateData: {
      resetLink: resetLink,
      userName: userEmail.split('@')[0],
      expirationHours: 1,
      companyName: 'DodaTech'
    },
    categories: ['password-reset', 'security'],
    tracking_settings: {
      open_tracking: { enable: true },
      click_tracking: { enable: true }
    }
  };

  try {
    await sgMail.send(msg);
    console.log('Password reset email sent');
  } catch (error) {
    console.error('Failed to send password reset:', error);
    throw error;
  }
}

Attachments and Personalization

async function sendInvoiceEmail(customerEmail, invoiceData, pdfBuffer) {
  const msg = {
    to: {
      email: customerEmail,
      name: invoiceData.customerName
    },
    from: {
      email: 'billing@dodatech.com',
      name: 'DodaTech Billing'
    },
    subject: `Invoice #${invoiceData.id}`,
    html: generateInvoiceHTML(invoiceData),
    attachments: [
      {
        content: pdfBuffer.toString('base64'),
        filename: `invoice-${invoiceData.id}.pdf`,
        type: 'application/pdf',
        disposition: 'attachment'
      }
    ],
    customArgs: {
      invoice_id: String(invoiceData.id),
      customer_id: String(invoiceData.customerId)
    },
    categories: ['invoice', 'billing']
  };

  await sgMail.send(msg);
}

Common Mistakes

1. Not Setting SendGrid API Key Before Sending

The API key must be set once at startup. Sending without setting the key results in authentication errors.

2. Using the Wrong Module

@sendgrid/mail is for sending email. @sendgrid/client is the base API client for all SendGrid API operations.

3. Not Handling Rate Limit Errors

When hitting rate limits, the API returns 429 errors. Implement retry logic with exponential backoff.

4. Forgetting to Validate Email Addresses

SendGrid rejects invalid email formats. Validate using a library like validator.isEmail().

5. Mixing Template and Content Parameters

When using templateId, do not include html or text content. Templates and raw content are mutually exclusive.

Practice Questions

  1. What package provides email sending in the SendGrid Node.js SDK?
  2. How do you set the API key?
  3. What is the templateId parameter used for?
  4. How do you add attachment data?
  5. What is the difference between @sendgrid/mail and @sendgrid/client?

Answers

  1. @sendgrid/mail. 2. sgMail.setApiKey('YOUR_API_KEY'). 3. It specifies the ID of a dynamic template to use. 4. Add an attachments array with base64 content, filename, type, and disposition. 5. @sendgrid/mail is a high-level mail helper; @sendgrid/client is the low-level API client.

Challenge

Build a Node.js email service that supports sending with dynamic templates, handles rate limits with retry logic, logs all sends and failures, and provides a health check endpoint showing SendGrid API status.

FAQ

What is @sendgrid/mail?

The official SendGrid npm package for sending transactional emails from Node.js.

How do I install the SendGrid Node.js SDK?

Run npm install @sendgrid/mail

Can I use async/await with the SendGrid SDK?

Yes, sgMail.send() returns a Promise that works with async/await.

Does the Node.js SDK support TypeScript?

Yes, it includes TypeScript type definitions.

How do I handle SendGrid errors in Node.js?

Catch the error and inspect error.response.body.errors for API error details.

Mini Project

Build an Express.js"Express" >}}.js API with SendGrid integration: POST /send for sending basic emails, POST /send-template for template-based emails, POST /send-invoice for invoice emails with attachments, and GET /status for checking SendGrid API health and usage statistics.

What's Next

  • Learn about the SendGrid Ruby SDK for Rails applications
  • Explore the SendGrid Go SDK for Microservices
  • Continue to email personalization with custom arguments and categories

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro