or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-delivery.mdattachments-content.mdemail-service.mdindex.mdmessage-construction.mdtemplates-personalization.mdtracking-analytics.md
tile.json

tessl/npm-sendgrid--mail

Twilio SendGrid NodeJS mail service for sending transactional and marketing emails with templates, attachments, and advanced delivery features.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@sendgrid/mail@8.1.x

To install, run

npx @tessl/cli install tessl/npm-sendgrid--mail@8.1.0

index.mddocs/

SendGrid Mail

SendGrid 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.

Package Information

  • Package Name: @sendgrid/mail
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install @sendgrid/mail

Core Imports

const sgMail = require('@sendgrid/mail');

For TypeScript:

import MailService = require("@sendgrid/mail/src/mail");

Access to the MailService class:

const { MailService } = require('@sendgrid/mail');

Basic Usage

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));

Architecture

SendGrid Mail is built around several key components:

  • MailService: Main service class providing configuration and sending functionality
  • Mail Class: Email message builder from @sendgrid/helpers for constructing complex emails
  • Data Types: Rich type system for emails, attachments, personalizations, and settings
  • Template System: Support for both legacy and dynamic templates with substitutions
  • Personalization: Per-recipient customization of content, headers, and metadata
  • Delivery Control: Scheduling, batching, IP pools, and suppression management

Capabilities

Email Sending Service

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 Sending Service

Message Construction

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);

Message Construction

Templates and Personalization

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' }
};

Templates and Personalization

Attachments and Content

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
}

Attachments and Content

Tracking and Analytics

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 };
}

Tracking and Analytics

Advanced Delivery

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 }
};

Advanced Delivery

Core Types

// 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;
}

Error Handling

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);
    }
  });