SendGrid Node.js SDK — Sending Emails with the Official JavaScript Library
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
- What package provides email sending in the SendGrid Node.js SDK?
- How do you set the API key?
- What is the templateId parameter used for?
- How do you add attachment data?
- What is the difference between @sendgrid/mail and @sendgrid/client?
Answers
@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/mailis a high-level mail helper;@sendgrid/clientis 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
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