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.00
# SendGrid Mail
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: @sendgrid/mail
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install @sendgrid/mail`
10
11
## Core Imports
12
13
```javascript
14
const sgMail = require('@sendgrid/mail');
15
```
16
17
For TypeScript:
18
19
```typescript
20
import MailService = require("@sendgrid/mail/src/mail");
21
```
22
23
Access to the MailService class:
24
25
```javascript
26
const { MailService } = require('@sendgrid/mail');
27
```
28
29
## Basic Usage
30
31
```javascript
32
const sgMail = require('@sendgrid/mail');
33
34
// Set your SendGrid API key
35
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
36
37
// Simple email
38
const msg = {
39
to: 'recipient@example.com',
40
from: 'sender@example.com',
41
subject: 'Hello from SendGrid',
42
text: 'Hello from SendGrid!',
43
html: '<strong>Hello from SendGrid!</strong>',
44
};
45
46
// Send email
47
sgMail.send(msg)
48
.then(() => console.log('Email sent'))
49
.catch((error) => console.error(error));
50
```
51
52
## Architecture
53
54
SendGrid Mail is built around several key components:
55
56
- **MailService**: Main service class providing configuration and sending functionality
57
- **Mail Class**: Email message builder from @sendgrid/helpers for constructing complex emails
58
- **Data Types**: Rich type system for emails, attachments, personalizations, and settings
59
- **Template System**: Support for both legacy and dynamic templates with substitutions
60
- **Personalization**: Per-recipient customization of content, headers, and metadata
61
- **Delivery Control**: Scheduling, batching, IP pools, and suppression management
62
63
## Capabilities
64
65
### Email Sending Service
66
67
Core email sending functionality with configuration, authentication, and delivery features. The main interface for sending single or multiple emails.
68
69
```javascript { .api }
70
// Default singleton instance
71
const sgMail = require('@sendgrid/mail');
72
73
// Configuration methods
74
sgMail.setApiKey(apiKey);
75
sgMail.setTwilioEmailAuth(username, password);
76
sgMail.setTimeout(timeout);
77
sgMail.setSubstitutionWrappers(left, right);
78
sgMail.setSecretRules(rules);
79
80
// Sending methods
81
sgMail.send(data, isMultiple, callback);
82
sgMail.sendMultiple(data, callback);
83
```
84
85
[Email Sending Service](./email-service.md)
86
87
### Message Construction
88
89
Email message building using the Mail class for complex email structures with attachments, personalizations, templates, and advanced settings.
90
91
```javascript { .api }
92
const { Mail } = require('@sendgrid/helpers').classes;
93
94
// Constructor and factory
95
const mail = new Mail(data);
96
const mail = Mail.create(data);
97
98
// Core setters
99
mail.setFrom(from);
100
mail.setSubject(subject);
101
mail.addTo(to, cc, bcc);
102
mail.setContent(content);
103
mail.setTemplateId(templateId);
104
```
105
106
[Message Construction](./message-construction.md)
107
108
### Templates and Personalization
109
110
Template integration with dynamic data, substitutions, and per-recipient personalizations for customized email content.
111
112
```javascript { .api }
113
// Template data
114
const msg = {
115
to: recipients,
116
from: 'sender@example.com',
117
templateId: 'd-1234567890abcdef',
118
dynamicTemplateData: { name: 'John', total: '$25.00' }
119
};
120
121
// Personalization for individual recipients
122
const personalization = {
123
to: ['user@example.com'],
124
dynamicTemplateData: { name: 'Alice' }
125
};
126
```
127
128
[Templates and Personalization](./templates-personalization.md)
129
130
### Attachments and Content
131
132
File attachment handling and content management including inline images, multiple content types, and rich media support.
133
134
```javascript { .api }
135
// Attachment structure
136
interface AttachmentData {
137
content: string; // Base64-encoded content
138
filename: string; // File name
139
type?: string; // MIME type
140
disposition?: string; // "attachment" or "inline"
141
contentId?: string; // For inline images
142
}
143
```
144
145
[Attachments and Content](./attachments-content.md)
146
147
### Tracking and Analytics
148
149
Email tracking configuration including open tracking, click tracking, subscription management, and Google Analytics integration.
150
151
```javascript { .api }
152
// Tracking settings structure
153
interface TrackingSettings {
154
clickTracking?: { enable?: boolean; enableText?: boolean };
155
openTracking?: { enable?: boolean; substitutionTag?: string };
156
subscriptionTracking?: { enable?: boolean; text?: string; html?: string };
157
ganalytics?: { enable?: boolean; utmSource?: string; utmCampaign?: string };
158
}
159
```
160
161
[Tracking and Analytics](./tracking-analytics.md)
162
163
### Advanced Delivery
164
165
Advanced email delivery features including scheduling, batching, IP pools, suppression management, and mail settings.
166
167
```javascript { .api }
168
// Advanced delivery options
169
const msg = {
170
to: 'recipient@example.com',
171
from: 'sender@example.com',
172
subject: 'Scheduled Email',
173
text: 'This email was scheduled',
174
sendAt: 1640995200, // Unix timestamp
175
batchId: 'batch_123',
176
ipPoolName: 'marketing_pool',
177
asm: { groupId: 123 }
178
};
179
```
180
181
[Advanced Delivery](./advanced-delivery.md)
182
183
## Core Types
184
185
```javascript { .api }
186
// Email address data
187
type EmailData = string | { name?: string; email: string };
188
189
// Mail content structure
190
interface MailContent {
191
type: string; // "text/plain" or "text/html"
192
value: string; // Content body
193
}
194
195
// Core mail data interface
196
interface MailData {
197
// Required: sender and content
198
from: EmailData;
199
text?: string;
200
html?: string;
201
templateId?: string;
202
content?: MailContent[];
203
204
// Recipients
205
to?: EmailData | EmailData[];
206
cc?: EmailData | EmailData[];
207
bcc?: EmailData | EmailData[];
208
209
// Message properties
210
subject?: string;
211
replyTo?: EmailData;
212
sendAt?: number;
213
214
// Advanced features
215
personalizations?: PersonalizationData[];
216
attachments?: AttachmentData[];
217
categories?: string[];
218
headers?: { [key: string]: string };
219
customArgs?: { [key: string]: any };
220
221
// Settings
222
mailSettings?: MailSettings;
223
trackingSettings?: TrackingSettings;
224
asm?: ASMOptions;
225
}
226
```
227
228
## Error Handling
229
230
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.
231
232
```javascript
233
sgMail.send(msg)
234
.then(() => {
235
console.log('Email sent successfully');
236
})
237
.catch((error) => {
238
console.error('Error sending email:', error);
239
240
if (error.response) {
241
console.error('Response body:', error.response.body);
242
}
243
});
244
```