Easy as cake e-mail sending from your Node.js applications
npx @tessl/cli install tessl/npm-nodemailer@7.0.00
# Nodemailer
1
2
Nodemailer is a comprehensive Node.js email delivery library that simplifies sending emails from Node.js applications through its easy-to-use API. It provides extensive SMTP transport support with authentication mechanisms including OAuth2, supports various email formats (plain text, HTML, attachments), offers built-in security features like DKIM signing and TLS encryption, includes template engine integration capabilities, and provides debugging and logging functionality.
3
4
## Package Information
5
6
- **Package Name**: nodemailer
7
- **Package Type**: npm
8
- **Language**: JavaScript/Node.js
9
- **Installation**: `npm install nodemailer`
10
11
## Core Imports
12
13
```javascript
14
const nodemailer = require('nodemailer');
15
```
16
17
ES Modules:
18
```javascript
19
import nodemailer from 'nodemailer';
20
// or
21
import { createTransport, createTestAccount, getTestMessageUrl } from 'nodemailer';
22
```
23
24
## Basic Usage
25
26
```javascript
27
const nodemailer = require('nodemailer');
28
29
// Create transporter object using SMTP transport
30
let transporter = nodemailer.createTransport({
31
host: 'smtp.gmail.com',
32
port: 587,
33
secure: false, // true for 465, false for other ports
34
auth: {
35
user: 'your.email@gmail.com',
36
pass: 'your-password'
37
}
38
});
39
40
// Define email options
41
let mailOptions = {
42
from: '"Sender Name" <sender@example.com>',
43
to: 'recipient@example.com',
44
subject: 'Hello ✔',
45
text: 'Hello world?',
46
html: '<b>Hello world?</b>'
47
};
48
49
// Send email
50
transporter.sendMail(mailOptions, (error, info) => {
51
if (error) {
52
return console.log(error);
53
}
54
console.log('Message sent: %s', info.messageId);
55
});
56
```
57
58
## Architecture
59
60
Nodemailer is built around several key components:
61
62
- **Transport Layer**: Pluggable transport system supporting SMTP, SMTP Pool, SES, Sendmail, Stream, and JSON transports
63
- **Mailer Class**: Core email sending interface with plugin support and event handling
64
- **Message Composition**: Advanced MIME message building with support for attachments, embedded images, and alternative content
65
- **Authentication**: Multiple authentication methods including basic auth, OAuth2, and custom SASL mechanisms
66
- **Security Features**: Built-in DKIM signing, TLS encryption, and proxy support
67
- **Testing Integration**: Ethereal Email service integration for development and testing
68
69
## Capabilities
70
71
### Transport Creation
72
73
Core functionality for creating email transport instances with various backends and configuration options.
74
75
```javascript { .api }
76
/**
77
* Creates a transport object for sending emails
78
* @param {Object|string} transporter - Transport configuration or connection URL
79
* @param {Object} [defaults] - Default message options
80
* @returns {Mailer} Mailer instance
81
*/
82
function createTransport(transporter, defaults);
83
```
84
85
[Transport Configuration](./transports.md)
86
87
### Email Sending
88
89
Main email sending functionality with support for various message formats, attachments, and delivery options.
90
91
```javascript { .api }
92
/**
93
* Sends an email message
94
* @param {Object} mailOptions - Email message configuration
95
* @param {Function} [callback] - Optional callback function
96
* @returns {Promise} Promise if no callback provided
97
*/
98
sendMail(mailOptions, callback);
99
100
interface MailOptions {
101
from?: string | Address;
102
to: string | string[] | Address | Address[];
103
cc?: string | string[] | Address | Address[];
104
bcc?: string | string[] | Address | Address[];
105
subject?: string;
106
text?: string | Buffer | NodeJS.ReadableStream;
107
html?: string | Buffer | NodeJS.ReadableStream;
108
attachments?: Attachment[];
109
headers?: Object;
110
priority?: 'high' | 'normal' | 'low';
111
date?: Date | string;
112
encoding?: string;
113
envelope?: Object;
114
messageId?: string;
115
replyTo?: string | string[] | Address | Address[];
116
inReplyTo?: string | string[];
117
references?: string | string[];
118
watchHtml?: string | Buffer | NodeJS.ReadableStream;
119
amp?: string | Buffer | NodeJS.ReadableStream;
120
icalEvent?: Object;
121
alternatives?: Alternative[];
122
list?: ListHeaders;
123
dsn?: Object;
124
sender?: string | Address;
125
raw?: string | Buffer;
126
}
127
128
interface Attachment {
129
filename?: string;
130
content?: string | Buffer | NodeJS.ReadableStream;
131
path?: string;
132
href?: string;
133
contentType?: string;
134
contentDisposition?: string;
135
cid?: string;
136
encoding?: string;
137
headers?: Object;
138
raw?: string | Buffer;
139
}
140
141
interface ListHeaders {
142
help?: string;
143
unsubscribe?: string | string[];
144
subscribe?: string | string[];
145
post?: string | string[];
146
owner?: string | string[];
147
archive?: string | string[];
148
id?: { url: string; comment?: string };
149
}
150
151
interface Address {
152
name?: string;
153
address: string;
154
}
155
156
interface Alternative {
157
contentType: string;
158
content: string | Buffer | NodeJS.ReadableStream;
159
encoding?: string;
160
raw?: string | Buffer;
161
}
162
```
163
164
[Email Sending](./sending.md)
165
166
### Test Account Management
167
168
Development and testing utilities for creating temporary email accounts and viewing sent messages.
169
170
```javascript { .api }
171
/**
172
* Creates a test account on Ethereal Email service
173
* @param {string} [apiUrl] - Optional API endpoint URL
174
* @param {Function} [callback] - Optional callback function
175
* @returns {Promise} Promise if no callback provided
176
*/
177
function createTestAccount(apiUrl, callback);
178
179
/**
180
* Generates URL to view sent test message on Ethereal
181
* @param {Object} info - Send result info object
182
* @returns {string|false} Message URL or false if not available
183
*/
184
function getTestMessageUrl(info);
185
```
186
187
[Testing Support](./testing.md)
188
189
### Plugin System
190
191
Extensible plugin architecture for customizing email processing and adding functionality.
192
193
```javascript { .api }
194
/**
195
* Adds a plugin to the mail processing pipeline
196
* @param {string} step - Processing step ('compile' or 'stream')
197
* @param {Function} plugin - Plugin function
198
* @returns {Mailer} this (chainable)
199
*/
200
use(step, plugin);
201
```
202
203
[Plugin Development](./plugins.md)
204
205
### Authentication Methods
206
207
Comprehensive authentication support including basic credentials, OAuth2, and custom SASL mechanisms.
208
209
```javascript { .api }
210
interface BasicAuth {
211
user: string;
212
pass: string;
213
}
214
215
interface OAuth2Auth {
216
type: 'OAuth2';
217
user: string;
218
clientId: string;
219
clientSecret: string;
220
refreshToken: string;
221
accessToken?: string;
222
expires?: Date;
223
accessUrl?: string;
224
}
225
226
interface CustomAuth {
227
type: string;
228
user: string;
229
method?: string;
230
options?: Object;
231
}
232
```
233
234
[Authentication](./authentication.md)
235
236
### Connection Management
237
238
Transport connection lifecycle management including verification, pooling, and cleanup.
239
240
```javascript { .api }
241
/**
242
* Verifies transport configuration
243
* @param {Function} [callback] - Optional callback function
244
* @returns {Promise} Promise if no callback provided
245
*/
246
verify(callback);
247
248
/**
249
* Checks if transport is idle (for pooled transports)
250
* @returns {boolean} True if idle
251
*/
252
isIdle();
253
254
/**
255
* Closes the transport connection
256
* @returns {void}
257
*/
258
close();
259
260
/**
261
* Sets a metadata value for the Mailer instance
262
* @param {string} key - Metadata key
263
* @param {*} value - Metadata value
264
* @returns {Mailer} this (chainable)
265
*/
266
set(key, value);
267
268
/**
269
* Gets a metadata value from the Mailer instance
270
* @param {string} key - Metadata key
271
* @returns {*} Metadata value or undefined
272
*/
273
get(key);
274
```
275
276
[Connection Management](./connection.md)
277
278
## Types
279
280
```javascript { .api }
281
/**
282
* Main Mailer class extending EventEmitter
283
*/
284
class Mailer extends EventEmitter {
285
constructor(transporter, options, defaults);
286
287
// Core methods
288
sendMail(mailOptions, callback);
289
use(step, plugin);
290
verify(callback);
291
isIdle();
292
close();
293
set(key, value);
294
get(key);
295
296
// Events emitted:
297
// - 'idle': Emitted when transport becomes idle (pooled transports)
298
// - 'error': Emitted when transport encounters an error
299
// - 'clear': Emitted when all connections are terminated
300
}
301
302
/**
303
* Transport configuration options
304
*/
305
interface TransportOptions {
306
// SMTP options
307
host?: string;
308
port?: number;
309
secure?: boolean;
310
auth?: BasicAuth | OAuth2Auth | CustomAuth;
311
tls?: TLSOptions;
312
service?: string; // Well-known service names like 'Gmail', 'Yahoo', etc.
313
314
// Pool options
315
pool?: boolean;
316
maxConnections?: number;
317
maxMessages?: number;
318
rateDelta?: number;
319
rateLimit?: number;
320
321
// General options
322
name?: string;
323
localAddress?: string;
324
logger?: boolean | Object;
325
debug?: boolean;
326
connectionTimeout?: number;
327
greetingTimeout?: number;
328
socketTimeout?: number;
329
proxy?: string;
330
331
// DKIM options
332
dkim?: DKIMOptions;
333
334
// Alternative transports
335
sendmail?: boolean;
336
path?: string;
337
args?: string[];
338
streamTransport?: boolean;
339
jsonTransport?: boolean;
340
SES?: SESOptions;
341
}
342
343
interface TLSOptions {
344
rejectUnauthorized?: boolean;
345
ciphers?: string;
346
minVersion?: string;
347
maxVersion?: string;
348
ca?: string | Buffer | Array<string | Buffer>;
349
cert?: string | Buffer;
350
key?: string | Buffer;
351
passphrase?: string;
352
}
353
354
interface DKIMOptions {
355
domainName: string;
356
keySelector: string;
357
privateKey: string | Buffer;
358
cacheDir?: string;
359
cacheTreshold?: number;
360
hashAlgo?: string;
361
skipFields?: string;
362
}
363
364
interface SESOptions {
365
sesClient?: any; // AWS SES v2 client instance
366
}
367
368
/**
369
* Send result information
370
*/
371
interface SentMessageInfo {
372
messageId: string;
373
envelope: {
374
from: string;
375
to: string[];
376
};
377
accepted: string[];
378
rejected: string[];
379
pending: string[];
380
response: string;
381
}
382
```