Twilio SendGrid NodeJS mail service for sending transactional and marketing emails with templates, attachments, and advanced delivery features.
—
Message construction provides fine-grained control over email building using the Mail class from @sendgrid/helpers. This allows for complex email structures with multiple content types, recipients, attachments, and advanced settings.
Create and initialize Mail instances for building complex email messages.
const { Mail } = require('@sendgrid/helpers').classes;
/**
* Create a Mail instance
* @param data - Optional initial mail data
*/
const mail = new Mail(data);
/**
* Create Mail instance from data (static factory method)
* @param data - Mail data object, array, or existing Mail instance
* @returns Mail instance or array of Mail instances
*/
const mail = Mail.create(data);
/**
* Populate Mail instance from data object
* @param data - Mail data to populate the instance
*/
mail.fromData(data);
/**
* Convert Mail instance to JSON format for SendGrid API
* @returns JSON representation of the email
*/
const jsonData = mail.toJSON();Usage Examples:
const { Mail } = require('@sendgrid/helpers').classes;
// Create empty mail instance
const mail = new Mail();
// Create mail with initial data
const mail = new Mail({
from: 'sender@example.com',
to: 'recipient@example.com',
subject: 'Hello World',
text: 'Hello from SendGrid!'
});
// Factory method
const mail = Mail.create({
from: 'sender@example.com',
to: 'recipient@example.com',
subject: 'Factory Created',
html: '<h1>Created with factory method</h1>'
});
// Create multiple mail instances
const mails = Mail.create([
{ from: 'sender@example.com', to: 'user1@example.com', subject: 'Message 1' },
{ from: 'sender@example.com', to: 'user2@example.com', subject: 'Message 2' }
]);Set fundamental email properties like sender, subject, and delivery timing.
/**
* Set the sender email address
* @param from - Email address string or object with name and email
*/
mail.setFrom(from);
/**
* Set the email subject line
* @param subject - Subject text
*/
mail.setSubject(subject);
/**
* Set reply-to email address
* @param replyTo - Reply-to email address
*/
mail.setReplyTo(replyTo);
/**
* Set scheduled send time
* @param sendAt - Unix timestamp for when to send the email
*/
mail.setSendAt(sendAt);
/**
* Set reply-to list for multiple reply addresses
* @param replyToList - Array of email address objects
*/
mail.setReplyToList(replyToList);Usage Examples:
// Basic sender and subject
mail.setFrom('noreply@example.com');
mail.setSubject('Important Update');
// Sender with display name
mail.setFrom({ email: 'support@example.com', name: 'Support Team' });
// Reply-to different from sender
mail.setReplyTo('support@example.com');
// Schedule email for future delivery
const futureTime = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now
mail.setSendAt(futureTime);
// Multiple reply-to addresses
mail.setReplyToList([
{ email: 'support@example.com', name: 'Support' },
{ email: 'sales@example.com', name: 'Sales' }
]);Add and manage email recipients including to, cc, and bcc addresses.
/**
* Convenience method for adding recipients
* @param to - To recipients (required)
* @param cc - CC recipients (optional)
* @param bcc - BCC recipients (optional)
*/
mail.addTo(to, cc, bcc);
/**
* Set personalizations array for complex recipient management
* @param personalizations - Array of personalization objects
*/
mail.setPersonalizations(personalizations);
/**
* Add a single personalization
* @param personalization - Personalization object for specific recipients
*/
mail.addPersonalization(personalization);Usage Examples:
// Simple recipient
mail.addTo('user@example.com');
// Multiple recipients with CC and BCC
mail.addTo(
['user1@example.com', 'user2@example.com'],
'manager@example.com',
'audit@example.com'
);
// Complex recipient management with personalizations
mail.addPersonalization({
to: [{ email: 'john@example.com', name: 'John Doe' }],
subject: 'Personal message for John',
dynamicTemplateData: { name: 'John', account: 'Premium' }
});
mail.addPersonalization({
to: [{ email: 'jane@example.com', name: 'Jane Smith' }],
subject: 'Personal message for Jane',
dynamicTemplateData: { name: 'Jane', account: 'Basic' }
});Manage email content including text, HTML, and multiple content types.
/**
* Set email content array
* @param content - Array of content objects with type and value
*/
mail.setContent(content);
/**
* Add a single content item
* @param content - Content object with type and value
*/
mail.addContent(content);
/**
* Add plain text content
* @param text - Plain text content
*/
mail.addTextContent(text);
/**
* Add HTML content
* @param html - HTML content
*/
mail.addHtmlContent(html);Usage Examples:
// Add plain text content
mail.addTextContent('This is the plain text version of the email.');
// Add HTML content
mail.addHtmlContent('<h1>HTML Email</h1><p>This is the <strong>HTML</strong> version.</p>');
// Set multiple content types
mail.setContent([
{ type: 'text/plain', value: 'Plain text version' },
{ type: 'text/html', value: '<h1>HTML version</h1>' }
]);
// Add custom content type
mail.addContent({
type: 'text/calendar',
value: 'BEGIN:VCALENDAR\nVERSION:2.0\n...'
});Integrate with SendGrid templates for dynamic content generation.
/**
* Set SendGrid template ID
* @param templateId - Template ID (dynamic templates start with 'd-')
*/
mail.setTemplateId(templateId);
/**
* Set dynamic template data for the entire email
* @param dynamicTemplateData - Object containing template variables
*/
mail.setDynamicTemplateData(dynamicTemplateData);
/**
* Set legacy template substitutions
* @param substitutions - Object mapping substitution keys to values
*/
mail.setSubstitutions(substitutions);
/**
* Set substitution wrapper characters
* @param wrappers - Array with left and right wrapper characters
*/
mail.setSubstitutionWrappers(wrappers);Usage Examples:
// Dynamic template (recommended)
mail.setTemplateId('d-1234567890abcdef');
mail.setDynamicTemplateData({
username: 'john_doe',
loginUrl: 'https://app.example.com/login',
supportEmail: 'support@example.com'
});
// Legacy template
mail.setTemplateId('legacy-template-id');
mail.setSubstitutions({
':username:': 'john_doe',
':loginUrl:': 'https://app.example.com/login'
});
// Custom substitution wrappers
mail.setSubstitutionWrappers(['[[', ']]']); // Use [[variable]] instead of {{variable}}Organize emails with categories, headers, and custom arguments for tracking and management.
/**
* Set email categories for organization and analytics
* @param categories - Array of category strings
*/
mail.setCategories(categories);
/**
* Add a single category
* @param category - Category string
*/
mail.addCategory(category);
/**
* Set custom SMTP headers
* @param headers - Object mapping header names to values
*/
mail.setHeaders(headers);
/**
* Add a single header
* @param key - Header name
* @param value - Header value
*/
mail.addHeader(key, value);
/**
* Set custom arguments for tracking
* @param customArgs - Object with custom tracking data
*/
mail.setCustomArgs(customArgs);
/**
* Set template sections for legacy templates
* @param sections - Object mapping section names to content
*/
mail.setSections(sections);Usage Examples:
// Email categories for analytics
mail.setCategories(['transactional', 'password-reset']);
mail.addCategory('high-priority');
// Custom headers
mail.setHeaders({
'X-Priority': '1',
'X-Mailer': 'MyApp v1.0'
});
mail.addHeader('X-Campaign-ID', 'spring-2024-promotion');
// Custom arguments for tracking
mail.setCustomArgs({
userId: '12345',
campaignId: 'welcome-series',
version: 'A'
});
// Template sections for legacy templates
mail.setSections({
':header:': '<h1>Welcome to Our Service</h1>',
':footer:': '<p>© 2024 Example Corp</p>'
});Configure delivery options, suppression management, and batch processing.
/**
* Set batch ID for grouping related emails
* @param batchId - Unique batch identifier
*/
mail.setBatchId(batchId);
/**
* Set IP pool for sending
* @param ipPoolName - Name of the IP pool to use
*/
mail.setIpPoolName(ipPoolName);
/**
* Set Advanced Suppression Management settings
* @param asm - ASM configuration object
*/
mail.setAsm(asm);
/**
* Control warning display for dynamic templates
* @param hide - Whether to hide warnings
*/
mail.setHideWarnings(hide);Usage Examples:
// Batch processing
mail.setBatchId('batch-2024-03-15-newsletter');
// IP pool selection
mail.setIpPoolName('marketing-pool');
// Suppression management
mail.setAsm({
groupId: 123,
groupsToDisplay: [123, 456, 789]
});
// Hide dynamic template warnings
mail.setHideWarnings(true);const { Mail } = require('@sendgrid/helpers').classes;
// Create comprehensive email
const mail = new Mail();
// Basic properties
mail.setFrom({ email: 'noreply@example.com', name: 'Example Corp' });
mail.setSubject('Welcome to Our Service');
mail.setReplyTo('support@example.com');
// Recipients with personalization
mail.addPersonalization({
to: [{ email: 'new-user@example.com', name: 'New User' }],
dynamicTemplateData: {
firstName: 'New',
accountType: 'Premium',
activationUrl: 'https://app.example.com/activate?token=abc123'
}
});
// Template
mail.setTemplateId('d-welcome-template-id');
// Organization
mail.setCategories(['transactional', 'welcome']);
mail.setCustomArgs({
userId: '54321',
signupSource: 'website'
});
// Custom headers
mail.addHeader('X-Campaign', 'user-onboarding');
// Advanced settings
mail.setBatchId('welcome-batch-2024-03');
mail.setIpPoolName('transactional-pool');
// Convert to JSON for sending
const emailData = mail.toJSON();
console.log('Email ready for sending:', emailData);Install with Tessl CLI
npx tessl i tessl/npm-sendgrid--mail