0
# Authentication
1
2
Comprehensive authentication support for various email providers and security mechanisms including basic credentials, OAuth2, and custom SASL methods.
3
4
## Capabilities
5
6
### Basic Authentication
7
8
Standard username and password authentication for SMTP servers.
9
10
```javascript { .api }
11
interface BasicAuth {
12
user: string; // Username or email address
13
pass: string; // Password or application-specific password
14
}
15
```
16
17
**Usage Examples:**
18
19
```javascript
20
// Basic SMTP authentication
21
const transporter = nodemailer.createTransport({
22
host: 'smtp.example.com',
23
port: 587,
24
secure: false,
25
auth: {
26
user: 'username@example.com',
27
pass: 'your-password'
28
}
29
});
30
31
// Gmail with App Password
32
const gmailTransporter = nodemailer.createTransport({
33
service: 'gmail',
34
auth: {
35
user: 'your.email@gmail.com',
36
pass: 'your-16-char-app-password'
37
}
38
});
39
```
40
41
### OAuth2 Authentication
42
43
OAuth2 authentication for services like Gmail, Outlook, and other providers supporting OAuth2.
44
45
```javascript { .api }
46
interface OAuth2Auth {
47
type: 'OAuth2'; // Authentication type
48
user: string; // User email address
49
clientId: string; // OAuth2 client ID
50
clientSecret: string; // OAuth2 client secret
51
refreshToken: string; // OAuth2 refresh token
52
accessToken?: string; // OAuth2 access token (optional, will be generated)
53
expires?: Date; // Access token expiry date
54
accessUrl?: string; // OAuth2 token endpoint URL
55
serviceClient?: string; // Service client identifier
56
privateKey?: string | Buffer; // Private key for service account (JWT)
57
}
58
```
59
60
**Usage Examples:**
61
62
Gmail OAuth2:
63
```javascript
64
const transporter = nodemailer.createTransport({
65
service: 'gmail',
66
auth: {
67
type: 'OAuth2',
68
user: 'your.email@gmail.com',
69
clientId: 'your-client-id.apps.googleusercontent.com',
70
clientSecret: 'your-client-secret',
71
refreshToken: 'your-refresh-token'
72
}
73
});
74
```
75
76
Outlook OAuth2:
77
```javascript
78
const transporter = nodemailer.createTransport({
79
service: 'Outlook365',
80
auth: {
81
type: 'OAuth2',
82
user: 'your.email@outlook.com',
83
clientId: 'your-azure-app-client-id',
84
clientSecret: 'your-azure-app-secret',
85
refreshToken: 'your-refresh-token',
86
accessUrl: 'https://login.microsoftonline.com/common/oauth2/v2.0/token'
87
}
88
});
89
```
90
91
Custom OAuth2 provider:
92
```javascript
93
const transporter = nodemailer.createTransport({
94
host: 'smtp.custom-provider.com',
95
port: 587,
96
secure: false,
97
auth: {
98
type: 'OAuth2',
99
user: 'user@custom-provider.com',
100
clientId: 'custom-client-id',
101
clientSecret: 'custom-client-secret',
102
refreshToken: 'custom-refresh-token',
103
accessUrl: 'https://custom-provider.com/oauth2/token'
104
}
105
});
106
```
107
108
### Custom Authentication Methods
109
110
Support for custom SASL authentication mechanisms and specialized authentication methods.
111
112
```javascript { .api }
113
interface CustomAuth {
114
type: string; // Custom authentication type
115
user: string; // Username
116
pass?: string; // Password (if required)
117
method?: string; // SASL method name
118
options?: Object; // Method-specific options
119
}
120
```
121
122
**Usage Examples:**
123
124
NTLM Authentication:
125
```javascript
126
const transporter = nodemailer.createTransport({
127
host: 'smtp.example.com',
128
port: 587,
129
secure: false,
130
auth: {
131
type: 'NTLM',
132
user: 'domain\\username',
133
pass: 'password',
134
options: {
135
domain: 'EXAMPLE-DOMAIN',
136
workstation: 'WORKSTATION-NAME'
137
}
138
}
139
});
140
```
141
142
Custom SASL method:
143
```javascript
144
const transporter = nodemailer.createTransport({
145
host: 'smtp.example.com',
146
port: 587,
147
secure: false,
148
auth: {
149
type: 'CUSTOM',
150
user: 'username',
151
method: 'CUSTOM-SASL-METHOD',
152
options: {
153
customParam1: 'value1',
154
customParam2: 'value2'
155
}
156
}
157
});
158
```
159
160
### Per-Message Authentication
161
162
Override transport authentication for individual messages.
163
164
```javascript { .api }
165
/**
166
* Per-message authentication override
167
* @param {Object} mailOptions - Mail options with custom auth
168
*/
169
const mailOptions = {
170
from: 'sender@example.com',
171
to: 'recipient@example.com',
172
subject: 'Custom Auth Message',
173
text: 'Message with custom authentication',
174
auth?: BasicAuth | OAuth2Auth | CustomAuth // Override transport auth
175
};
176
```
177
178
**Usage Examples:**
179
180
```javascript
181
// Send email with different OAuth2 credentials
182
const mailOptions = {
183
from: 'sender@example.com',
184
to: 'recipient@example.com',
185
subject: 'Different Auth',
186
text: 'Message sent with different authentication',
187
auth: {
188
type: 'OAuth2',
189
user: 'different.user@gmail.com',
190
clientId: 'different-client-id',
191
clientSecret: 'different-client-secret',
192
refreshToken: 'different-refresh-token'
193
}
194
};
195
196
transporter.sendMail(mailOptions, callback);
197
```
198
199
### Authentication Events and Token Management
200
201
OAuth2 token management and authentication event handling.
202
203
```javascript { .api }
204
/**
205
* OAuth2 token refresh event
206
* Emitted when OAuth2 tokens are refreshed
207
*/
208
transporter.on('token', (token) => {
209
// Handle token update
210
console.log('New access token:', token.accessToken);
211
console.log('Token expires:', token.expires);
212
213
// Store updated token for future use
214
saveTokenToDatabase(token);
215
});
216
217
/**
218
* Authentication error event
219
* Emitted when authentication fails
220
*/
221
transporter.on('error', (error) => {
222
if (error.code === 'EAUTH') {
223
console.log('Authentication failed:', error.message);
224
// Handle authentication error
225
}
226
});
227
```
228
229
**Usage Examples:**
230
231
Token refresh handling:
232
```javascript
233
const transporter = nodemailer.createTransport({
234
service: 'gmail',
235
auth: {
236
type: 'OAuth2',
237
user: 'user@gmail.com',
238
clientId: 'client-id',
239
clientSecret: 'client-secret',
240
refreshToken: 'refresh-token'
241
}
242
});
243
244
// Listen for token updates
245
transporter.on('token', (token) => {
246
console.log('Token refreshed!');
247
console.log('Access Token:', token.accessToken);
248
console.log('Expires:', new Date(token.expires));
249
250
// Update stored credentials
251
updateStoredToken(token);
252
});
253
```
254
255
### Authentication Provisioning
256
257
Custom OAuth2 token provisioning for advanced use cases.
258
259
```javascript { .api }
260
/**
261
* Custom OAuth2 token provisioning callback
262
* @param {Object} auth - Authentication object
263
* @param {Function} callback - Callback function (error, accessToken, expires)
264
*/
265
transporter.set('oauth2_provision_cb', (auth, callback) => {
266
// Custom token provisioning logic
267
getCustomAccessToken(auth, (error, accessToken, expires) => {
268
if (error) {
269
return callback(error);
270
}
271
callback(null, accessToken, expires);
272
});
273
});
274
```
275
276
**Usage Examples:**
277
278
```javascript
279
// Custom token provisioning
280
const transporter = nodemailer.createTransport({
281
service: 'gmail',
282
auth: {
283
type: 'OAuth2',
284
user: 'user@gmail.com',
285
// Other OAuth2 settings...
286
}
287
});
288
289
// Set custom provisioning callback
290
transporter.set('oauth2_provision_cb', (auth, callback) => {
291
// Implement custom logic to get access token
292
// For example, from a token management service
293
tokenService.getAccessToken(auth.user, (error, token) => {
294
if (error) {
295
return callback(error);
296
}
297
298
callback(null, token.accessToken, token.expires);
299
});
300
});
301
```
302
303
### Well-known Service Authentication
304
305
Pre-configured authentication settings for popular email services.
306
307
```javascript { .api }
308
// Gmail
309
const gmailAuth = {
310
service: 'gmail',
311
auth: {
312
user: 'user@gmail.com',
313
pass: 'app-specific-password'
314
}
315
};
316
317
// Outlook/Hotmail
318
const outlookAuth = {
319
service: 'Outlook365',
320
auth: {
321
user: 'user@outlook.com',
322
pass: 'password'
323
}
324
};
325
326
// Yahoo
327
const yahooAuth = {
328
service: 'Yahoo',
329
auth: {
330
user: 'user@yahoo.com',
331
pass: 'app-password'
332
}
333
};
334
```
335
336
**Usage Examples:**
337
338
```javascript
339
// Pre-configured service authentication
340
const transporters = {
341
gmail: nodemailer.createTransport({
342
service: 'gmail',
343
auth: {
344
user: 'user@gmail.com',
345
pass: 'app-password'
346
}
347
}),
348
349
outlook: nodemailer.createTransport({
350
service: 'Outlook365',
351
auth: {
352
user: 'user@outlook.com',
353
pass: 'password'
354
}
355
}),
356
357
yahoo: nodemailer.createTransport({
358
service: 'Yahoo',
359
auth: {
360
user: 'user@yahoo.com',
361
pass: 'app-password'
362
}
363
})
364
};
365
```
366
367
### Security Considerations
368
369
Authentication security best practices and error handling.
370
371
**Best Practices:**
372
373
1. **Use App Passwords**: For services like Gmail, use application-specific passwords instead of account passwords
374
2. **OAuth2 Preferred**: Use OAuth2 when available for better security and token refresh capabilities
375
3. **Secure Storage**: Store credentials securely, never in source code
376
4. **Token Refresh**: Handle OAuth2 token refresh automatically
377
5. **Error Handling**: Implement proper error handling for authentication failures
378
379
**Common Authentication Errors:**
380
381
```javascript
382
// Handle authentication errors
383
transporter.sendMail(mailOptions, (error, info) => {
384
if (error) {
385
switch (error.code) {
386
case 'EAUTH':
387
console.log('Authentication failed');
388
break;
389
case 'ESOCKET':
390
console.log('Connection failed');
391
break;
392
default:
393
console.log('Other error:', error.message);
394
}
395
return;
396
}
397
console.log('Message sent:', info.messageId);
398
});
399
```