CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sendgrid--mail

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

Pending
Overview
Eval results
Files

email-service.mddocs/

Email Sending Service

The email sending service provides the main interface for sending emails through SendGrid. It includes configuration methods, authentication setup, and sending capabilities for both single and multiple emails.

Capabilities

Service Configuration

Configure the SendGrid service with API keys, authentication, and client settings.

/**
 * Set the SendGrid API key for authentication
 * @param apiKey - Your SendGrid API key
 */
sgMail.setApiKey(apiKey);

/**
 * Set Twilio Email authentication credentials
 * @param username - Twilio username
 * @param password - Twilio password  
 */
sgMail.setTwilioEmailAuth(username, password);

/**
 * Set request timeout in milliseconds
 * @param timeout - Timeout value in milliseconds
 */
sgMail.setTimeout(timeout);

/**
 * Set template substitution wrapper characters
 * @param left - Left wrapper character (default: '{{')
 * @param right - Right wrapper character (default: '}}')
 */
sgMail.setSubstitutionWrappers(left, right);

Usage Examples:

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

// Basic setup
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

// Configure timeout for slow connections
sgMail.setTimeout(10000); // 10 second timeout

// Custom substitution wrappers for templates
sgMail.setSubstitutionWrappers('[[', ']]'); // Use [[variable]] instead of {{variable}}

// Twilio Email Auth (alternative to API key)
sgMail.setTwilioEmailAuth('your_username', 'your_password');

Content Security

Prevent sensitive data from being sent in emails through content filtering rules.

/**
 * Set rules for filtering sensitive content from emails
 * @param rules - Array of strings, RegExp objects, or rule objects
 */
sgMail.setSecretRules(rules);

Usage Examples:

// Simple string patterns
sgMail.setSecretRules([
  'password',
  'secret',
  'confidential'
]);

// Regular expression patterns
sgMail.setSecretRules([
  /\b\d{4}-\d{4}-\d{4}-\d{4}\b/, // Credit card pattern
  /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i // Email pattern
]);

// Rule objects with names
sgMail.setSecretRules([
  {
    pattern: /\bssn:\s*\d{3}-\d{2}-\d{4}\b/i,
    name: 'Social Security Number'
  }
]);

Email Sending

Send single or multiple emails with full control over delivery options.

/**
 * Send an email or array of emails
 * @param data - Email data object or array of email data objects
 * @param isMultiple - Flag indicating multiple recipient handling (optional)
 * @param callback - Optional callback function (error, result) => void
 * @returns Promise resolving to send result
 */
sgMail.send(data, isMultiple, callback);

/**
 * Send multiple emails (convenience method)
 * @param data - Array of email data objects
 * @param callback - Optional callback function (error, result) => void  
 * @returns Promise resolving to send results array
 */
sgMail.sendMultiple(data, callback);

Usage Examples:

// Single email with Promise
const msg = {
  to: 'recipient@example.com',
  from: 'sender@example.com',
  subject: 'Hello World',
  text: 'Hello from SendGrid!',
  html: '<h1>Hello from SendGrid!</h1>'
};

sgMail.send(msg)
  .then(() => console.log('Email sent'))
  .catch(error => console.error(error));

// Single email with callback
sgMail.send(msg, (error, result) => {
  if (error) {
    console.error('Error:', error);
  } else {
    console.log('Success:', result);
  }
});

// Multiple emails in parallel
const messages = [
  {
    to: 'user1@example.com',
    from: 'noreply@example.com',
    subject: 'Welcome User 1',
    text: 'Welcome to our service!'
  },
  {
    to: 'user2@example.com', 
    from: 'noreply@example.com',
    subject: 'Welcome User 2',
    text: 'Welcome to our service!'
  }
];

sgMail.sendMultiple(messages)
  .then(results => console.log('All emails sent:', results))
  .catch(error => console.error('Error sending emails:', error));

// Single email to multiple recipients (each gets individual email)
const msgToMultiple = {
  to: ['user1@example.com', 'user2@example.com'],
  from: 'sender@example.com',
  subject: 'Broadcast Message',
  text: 'This message goes to multiple recipients'
};

sgMail.send(msgToMultiple, true) // isMultiple = true
  .then(() => console.log('Emails sent to all recipients'))
  .catch(error => console.error(error));

MailService Class

Create custom service instances with independent configuration.

/**
 * MailService class for creating independent service instances
 */
const { MailService } = require('@sendgrid/mail');

/**
 * Create a new MailService instance
 */
const customService = new MailService();

// All configuration methods available on custom instances
customService.setApiKey(apiKey);
customService.setTwilioEmailAuth(username, password);
customService.setTimeout(timeout);
customService.setSubstitutionWrappers(left, right);
customService.setSecretRules(rules);
customService.send(data, isMultiple, callback);
customService.sendMultiple(data, callback);

Usage Examples:

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

// Create separate services for different use cases
const transactionalService = new MailService();
const marketingService = new MailService();

// Configure each service independently
transactionalService.setApiKey(process.env.SENDGRID_TRANSACTIONAL_KEY);
marketingService.setApiKey(process.env.SENDGRID_MARKETING_KEY);

// Set different timeouts
transactionalService.setTimeout(5000);  // Fast timeout for transactional
marketingService.setTimeout(30000);     // Longer timeout for marketing

// Use services independently
transactionalService.send(orderConfirmation);
marketingService.send(newsletter);

Error Handling

The service returns detailed error information for debugging and monitoring.

sgMail.send(invalidMsg)
  .catch(error => {
    console.error('SendGrid Error:', error.message);
    
    // HTTP response details
    if (error.response) {
      console.error('Status Code:', error.response.statusCode);
      console.error('Response Body:', error.response.body);
      
      // SendGrid-specific error details
      if (error.response.body.errors) {
        error.response.body.errors.forEach(err => {
          console.error(`Error: ${err.message} (Field: ${err.field})`);
        });
      }
    }
  });

Authentication Methods

SendGrid Mail supports two authentication methods:

  1. API Key Authentication (Recommended):

    sgMail.setApiKey('SG.your-api-key-here');
  2. Twilio Email Authentication:

    sgMail.setTwilioEmailAuth('your-username', 'your-password');

The API key method is recommended for most use cases as it provides better security and easier credential management.

Content Filtering

Content filtering helps prevent accidental transmission of sensitive data. When secret rules are triggered, the send operation will throw an error before the email is transmitted:

sgMail.setSecretRules(['password', 'secret']);

const badMsg = {
  to: 'user@example.com',
  from: 'sender@example.com', 
  subject: 'Your account info',
  text: 'Your password is: secret123' // This will trigger the filter
};

sgMail.send(badMsg)
  .catch(error => {
    // Error: The pattern '/secret/' was found in the Mail content!
    console.error(error.message);
  });

Install with Tessl CLI

npx tessl i tessl/npm-sendgrid--mail

docs

advanced-delivery.md

attachments-content.md

email-service.md

index.md

message-construction.md

templates-personalization.md

tracking-analytics.md

tile.json