Twilio SendGrid NodeJS mail service for sending transactional and marketing emails with templates, attachments, and advanced delivery features.
npx @tessl/cli install tessl/npm-sendgrid--mail@8.1.0SendGrid Mail is a comprehensive Node.js library for sending transactional and marketing emails using the Twilio SendGrid Web API v3. It provides a powerful, feature-rich API for email delivery with support for templates, attachments, personalizations, tracking, scheduling, and advanced delivery features.
npm install @sendgrid/mailconst sgMail = require('@sendgrid/mail');For TypeScript:
import MailService = require("@sendgrid/mail/src/mail");Access to the MailService class:
const { MailService } = require('@sendgrid/mail');const sgMail = require('@sendgrid/mail');
// Set your SendGrid API key
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
// Simple email
const msg = {
to: 'recipient@example.com',
from: 'sender@example.com',
subject: 'Hello from SendGrid',
text: 'Hello from SendGrid!',
html: '<strong>Hello from SendGrid!</strong>',
};
// Send email
sgMail.send(msg)
.then(() => console.log('Email sent'))
.catch((error) => console.error(error));SendGrid Mail is built around several key components:
Core email sending functionality with configuration, authentication, and delivery features. The main interface for sending single or multiple emails.
// Default singleton instance
const sgMail = require('@sendgrid/mail');
// Configuration methods
sgMail.setApiKey(apiKey);
sgMail.setTwilioEmailAuth(username, password);
sgMail.setTimeout(timeout);
sgMail.setSubstitutionWrappers(left, right);
sgMail.setSecretRules(rules);
// Sending methods
sgMail.send(data, isMultiple, callback);
sgMail.sendMultiple(data, callback);Email message building using the Mail class for complex email structures with attachments, personalizations, templates, and advanced settings.
const { Mail } = require('@sendgrid/helpers').classes;
// Constructor and factory
const mail = new Mail(data);
const mail = Mail.create(data);
// Core setters
mail.setFrom(from);
mail.setSubject(subject);
mail.addTo(to, cc, bcc);
mail.setContent(content);
mail.setTemplateId(templateId);Template integration with dynamic data, substitutions, and per-recipient personalizations for customized email content.
// Template data
const msg = {
to: recipients,
from: 'sender@example.com',
templateId: 'd-1234567890abcdef',
dynamicTemplateData: { name: 'John', total: '$25.00' }
};
// Personalization for individual recipients
const personalization = {
to: ['user@example.com'],
dynamicTemplateData: { name: 'Alice' }
};File attachment handling and content management including inline images, multiple content types, and rich media support.
// Attachment structure
interface AttachmentData {
content: string; // Base64-encoded content
filename: string; // File name
type?: string; // MIME type
disposition?: string; // "attachment" or "inline"
contentId?: string; // For inline images
}Email tracking configuration including open tracking, click tracking, subscription management, and Google Analytics integration.
// Tracking settings structure
interface TrackingSettings {
clickTracking?: { enable?: boolean; enableText?: boolean };
openTracking?: { enable?: boolean; substitutionTag?: string };
subscriptionTracking?: { enable?: boolean; text?: string; html?: string };
ganalytics?: { enable?: boolean; utmSource?: string; utmCampaign?: string };
}Advanced email delivery features including scheduling, batching, IP pools, suppression management, and mail settings.
// Advanced delivery options
const msg = {
to: 'recipient@example.com',
from: 'sender@example.com',
subject: 'Scheduled Email',
text: 'This email was scheduled',
sendAt: 1640995200, // Unix timestamp
batchId: 'batch_123',
ipPoolName: 'marketing_pool',
asm: { groupId: 123 }
};// Email address data
type EmailData = string | { name?: string; email: string };
// Mail content structure
interface MailContent {
type: string; // "text/plain" or "text/html"
value: string; // Content body
}
// Core mail data interface
interface MailData {
// Required: sender and content
from: EmailData;
text?: string;
html?: string;
templateId?: string;
content?: MailContent[];
// Recipients
to?: EmailData | EmailData[];
cc?: EmailData | EmailData[];
bcc?: EmailData | EmailData[];
// Message properties
subject?: string;
replyTo?: EmailData;
sendAt?: number;
// Advanced features
personalizations?: PersonalizationData[];
attachments?: AttachmentData[];
categories?: string[];
headers?: { [key: string]: string };
customArgs?: { [key: string]: any };
// Settings
mailSettings?: MailSettings;
trackingSettings?: TrackingSettings;
asm?: ASMOptions;
}SendGrid Mail uses Promises and provides detailed error information through ResponseError objects. Common error scenarios include authentication failures, invalid email addresses, template errors, and API rate limits.
sgMail.send(msg)
.then(() => {
console.log('Email sent successfully');
})
.catch((error) => {
console.error('Error sending email:', error);
if (error.response) {
console.error('Response body:', error.response.body);
}
});