nodemailer 2.6.3 → 2.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +4 -1113
  3. package/package.json +16 -16
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.7.0 2016-12-08
4
+
5
+ * Bumped mailcomposer that generates encoded-words differently which might break some tests
6
+
3
7
  ## 2.6.0 2016-09-05
4
8
 
5
9
  * Added new options disableFileAccess and disableUrlAccess
package/README.md CHANGED
@@ -2,1122 +2,13 @@
2
2
 
3
3
  Send e-mails from Node.js – easy as cake! 🍰✉️
4
4
 
5
- <a href="https://gitter.im/nodemailer/nodemailer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"><img src="https://badges.gitter.im/Join Chat.svg" alt="Gitter chat" height="18"></a> <a href="http://travis-ci.org/nodemailer/nodemailer"><img src="https://secure.travis-ci.org/nodemailer/nodemailer.svg" alt="Build Status" height="18"></a> <a href="http://badge.fury.io/js/nodemailer"><img src="https://badge.fury.io/js/nodemailer.svg" alt="NPM version" height="18"></a> <a href="https://www.npmjs.com/package/nodemailer"><img src="https://img.shields.io/npm/dt/nodemailer.svg" alt="NPM downloads" height="18"></a>
5
+ <a href="http://badge.fury.io/js/nodemailer"><img src="https://badge.fury.io/js/nodemailer.svg" alt="NPM version" height="18"></a> <a href="https://www.npmjs.com/package/nodemailer"><img src="https://img.shields.io/npm/dt/nodemailer.svg" alt="NPM downloads" height="18"></a>
6
6
 
7
- ## Other similar packages you might be interested in
7
+ ### Community version
8
8
 
9
- * **[smtp-server](https://github.com/andris9/smtp-server)** add SMTP server interface to your application
10
- * **[smtp-server](https://github.com/nodemailer/smtp-connection)** – connect to SMTP servers from your application
11
- * **[zone-mta](https://github.com/zone-eu/zone-mta)** – full featured outbound MTA built using smtp-connection and smtp-server modules
9
+ This is the community version of Nodemailer ([usage docs](https://community.nodemailer.com/)). Community meaning minimal maintenance and support by the author.
12
10
 
13
- # Notes and information
14
- ## Nodemailer supports
15
- - **Node.js 0.10+**, no ES6 shenanigans used that would break your production app
16
- - **Unicode** to use any characters, including full emoji support 👻
17
- - **Windows** – you can install it with _npm_ on Windows just like any other module, there are no compiled dependencies. Use it from Azure or from your Windows box hassle free.
18
- - **HTML content** as well as **plain text** alternative
19
- - **Attachments** (including attachment **streaming** for sending larger files)
20
- - **Embedded images** in HTML
21
- - Secure e-mail delivery using **SSL/STARTTLS**
22
- - Different **transport methods**, either using built-in SMTP transports or from external plugins
23
- - Custom **plugin support** for manipulating messages (add DKIM signatures, use markdown content instead of HTML etc.)
24
- - Sane **XOAUTH2** login with automatic access token generation (and feedback about the updated tokens)
25
- - Simple built-in **templating** using [node-email-templates](https://github.com/niftylettuce/node-email-templates) or custom renderer
26
- - **Proxies** for SMTP connections (SOCKS, HTTP and custom connections)
27
-
28
- > See Nodemailer [homepage](http://nodemailer.com/) for complete documentation
29
-
30
- ## Support Nodemailer development
31
- [![Donate to author](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DB26KWR2BQX5W)
32
-
33
- If you want to support with Bitcoins, then my wallet address is `15Z8ADxhssKUiwP3jbbqJwA21744KMCfTM`
34
-
35
- # TL;DR Usage Example
36
- This is a complete example to send an e-mail with plaintext and HTML body
37
-
38
- ```javascript
39
- var nodemailer = require('nodemailer');
40
-
41
- // create reusable transporter object using the default SMTP transport
42
- var transporter = nodemailer.createTransport('smtps://user%40gmail.com:pass@smtp.gmail.com');
43
-
44
- // setup e-mail data with unicode symbols
45
- var mailOptions = {
46
- from: '"Fred Foo 👥" <foo@blurdybloop.com>', // sender address
47
- to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers
48
- subject: 'Hello ✔', // Subject line
49
- text: 'Hello world 🐴', // plaintext body
50
- html: '<b>Hello world 🐴</b>' // html body
51
- };
52
-
53
- // send mail with defined transport object
54
- transporter.sendMail(mailOptions, function(error, info){
55
- if(error){
56
- return console.log(error);
57
- }
58
- console.log('Message sent: ' + info.response);
59
- });
60
- ```
61
-
62
- > To use Gmail you may need to configure ["Allow Less Secure Apps"](https://www.google.com/settings/security/lesssecureapps) in your Gmail account unless you are using 2FA in which case you would have to create an [Application Specific](https://security.google.com/settings/security/apppasswords) password. You also may need to unlock your account with ["Allow access to your Google account"](https://accounts.google.com/DisplayUnlockCaptcha) to use SMTP.
63
-
64
- # Setting up
65
- Install with npm
66
-
67
- ```
68
- npm install nodemailer
69
- ```
70
-
71
- To send e-mails you need a transporter object
72
-
73
- ```javascript
74
- var transporter = nodemailer.createTransport(transport[, defaults])
75
- ```
76
-
77
- Where
78
- - **transporter** is going to be an object that is able to send mail
79
- - **transport** is the transport configuration object, connection url or a transport plugin instance
80
- - **defaults** is an object that defines default values for mail options
81
-
82
- > You have to create the transporter object only once. If you already have a transporter object you can use it to send mail as much as you like.
83
-
84
- ## Send using SMTP
85
-
86
- ### SMTP? Say what?
87
-
88
- You might wonder why you would need to set something up while in comparison
89
- PHP's [mail](http://php.net/manual/en/function.mail.php) command works out of
90
- the box with no special configuration whatsoever. Just call `mail(...)` and
91
- you're already sending mail. So what's going on in Node.js?
92
-
93
- The difference is in the software stack required for your application to work.
94
- While Node.js stack is thin, all you need for your app to work is the *node*
95
- binary, then PHP's stack is fat. The server you're running your PHP code on has
96
- several different components installed. Firstly the PHP interpreter itself. Then
97
- there's some kind of web server, most probably Apache or Nginx. Web server needs
98
- some way to interact with the PHP interpreter, so you have a CGI process
99
- manager. There might be MySQL also running in the same host. Depending on the
100
- installation type you might even have imagemagick executables or other helpers
101
- lying around somewhere. And finally, you have the *sendmail* binary.
102
-
103
- What PHP's `mail()` call actually does is that it passes your mail data to
104
- sendmail's *stdin* and thats it, no magic involved. *sendmail* does all the
105
- heavy lifting of queueing your message and trying to send it to the recipients'
106
- MX mail server. Usually this works because the server is an actual web server
107
- accessible from the web and has also gathered some mail sending reputation
108
- because PHP web hosts have been around for, like, forever.
109
-
110
- Node.js apps on the other hand might run wherever, usually on some really new
111
- VPS behind an IP address that has no sending reputation at all. Or the IP is
112
- dynamically allocated which is the fastest way to get rejected while trying to
113
- send mail. So while you might actually emulate the same behavior with Nodemailer
114
- by using either the [sendmail transport](https://github.com/andris9/nodemailer-sendmail-transport)
115
- or so called *direct* transport, then this does not guarantee yet any
116
- deliverability. Recipient's server might reject connection from your app because
117
- your server has dynamic IP address. Or it might reject or send your mail
118
- straight to spam mailbox because your IP address is not yet trusted.
119
-
120
- So the reason why PHP's `mail` works and Node.js's does not is that your PHP
121
- hosting provider has put in a lot of work over several years to provide a solid
122
- mail sending infrastructure. It is not about PHP at all, it is about the
123
- infrastructure around it.
124
-
125
- ### Set up SMTP
126
-
127
- You can use 3 kinds of different approaches when using SMTP
128
-
129
- 1. *normal* usage. No specific configuration needed. For every e-mail a new SMTP connection is created and message is sent immediately. Used when the amount of sent messages is low.
130
- 1. *pooled* usage. Set *pool* option to `true` to use it. A fixed amount of pooled connections are used to send messages. Useful when you have a large number of messages that you want to send in batches.
131
- 1. *direct* usage. Set *direct* option to `true` to use it. SMTP connection is opened directly to recipients MX server, skipping any local SMTP relays. useful when you do not have a SMTP relay to use. Riskier though since messages from untrusted servers usually end up in the Spam folder.
132
-
133
- ```javascript
134
- var transporter = nodemailer.createTransport(options[, defaults])
135
- ```
136
-
137
- Where
138
-
139
- * **options** defines connection data
140
- * **options.pool** if set to `true` uses pooled connections (defaults to `false`), otherwise creates a new connection for every e-mail.
141
- * **options.direct** if set to `true`, bypasses MTA relay and connects directly to recipients MX. Easier to set up but has higher chances of ending up in the Spam folder
142
- * **options.service** can be set to the name of a well-known service so you don't have to input the `port`, `host`, and `secure` options (see [Using well-known services](#using-well-known-services))
143
- * **options.port** is the port to connect to (defaults to 25 or 465)
144
- * **options.host** is the hostname or IP address to connect to (defaults to `'localhost'`)
145
- * **options.secure** if `true`the connection will only use TLS. If `false` (the default), TLS may still be upgraded to if available via the STARTTLS command.
146
- * **options.ignoreTLS** if this is `true` and `secure` is false, TLS will not be used (either to connect, or as a STARTTLS connection upgrade command).
147
- * **options.requireTLS** if this is `true` and `secure` is false, it forces Nodemailer to use STARTTLS even if the server does not advertise support for it.
148
- * **options.tls** defines additional [node.js TLSSocket options](https://nodejs.org/api/tls.html#tls_class_tls_tlssocket) to be passed to the socket constructor, eg. *{rejectUnauthorized: true}*.
149
- * **options.auth** defines authentication data (see [authentication](#authentication) section below)
150
- * **options.authMethod** defines preferred authentication method, eg. 'PLAIN'
151
- * **options.name** optional hostname of the client, used for identifying to the server
152
- * **options.localAddress** is the local interface to bind to for network connections
153
- * **options.connectionTimeout** how many milliseconds to wait for the connection to establish
154
- * **options.greetingTimeout** how many milliseconds to wait for the greeting after connection is established
155
- * **options.socketTimeout** how many milliseconds of inactivity to allow
156
- * **options.logger** optional [bunyan](https://github.com/trentm/node-bunyan) compatible logger instance. If set to `true` then logs to console. If value is not set or is `false` then nothing is logged
157
- * **options.debug** if set to true, then logs SMTP traffic, otherwise logs only transaction events. This option requires **options.logger** to be set, otherwise there is nowhere to log the transaction data
158
- * **options.maxConnections** available only if *pool* is set to `true`. (defaults to 5) is the count of maximum simultaneous connections to make against the SMTP server
159
- * **options.maxMessages** available only if *pool* is set to `true`. (defaults to 100) limits the message count to be sent using a single connection. After maxMessages messages the connection is dropped and a new one is created for the following messages
160
- * **options.rateLimit** available only if *pool* is set to `true`. (defaults to `false`) limits the message count to be sent in a second. Once rateLimit is reached, sending is paused until the end of the second. This limit is shared between connections, so if one connection uses up the limit, then other connections are paused as well
161
- * **options.disableFileAccess** if true, then does not allow to use files as content. Use it when you want to use JSON data from untrusted source as the email. If an attachment or message node tries to fetch something from a file the sending returns an error
162
- * **options.disableUrlAccess** if true, then does not allow to use Urls as content
163
-
164
- **Examples**
165
-
166
- ```javascript
167
- var smtpConfig = {
168
- host: 'smtp.gmail.com',
169
- port: 465,
170
- secure: true, // use SSL
171
- auth: {
172
- user: 'user@gmail.com',
173
- pass: 'pass'
174
- }
175
- };
176
-
177
- var poolConfig = {
178
- pool: true,
179
- host: 'smtp.gmail.com',
180
- port: 465,
181
- secure: true, // use SSL
182
- auth: {
183
- user: 'user@gmail.com',
184
- pass: 'pass'
185
- }
186
- };
187
-
188
- var directConfig = {
189
- name: 'hostname' // must be the same that can be reverse resolved by DNS for your IP
190
- };
191
- ```
192
-
193
- Alternatively you could use connection url. Use `smtp:`, `smtps:` or `direct:` as the protocol.
194
-
195
- ```javascript
196
- var smtpConfig = 'smtps://user%40gmail.com:pass@smtp.gmail.com';
197
- var poolConfig = 'smtps://user%40gmail.com:pass@smtp.gmail.com/?pool=true';
198
- var directConfig = 'direct:?name=hostname';
199
- ```
200
-
201
- ### Proxy support
202
-
203
- Nodemailer supports out of the box HTTP and SOCKS proxies for SMTP connections with the `proxy` configuration option. You can also use a custom connection handler with the `getSocket` method.
204
-
205
- Proxy configuration is provided as a connection url where used protocol defines proxy protocol (eg. `'socks://hostname:port'` for a SOCKS5 proxy). You can also use authentication by passing proxy username and password into the configuration url (eg `'socks://username:password@hostname:port'`)
206
-
207
- #### HTTP CONNECT tunnel
208
-
209
- HTTP proxy must support CONNECT tunnels (also called "SSL support") to SMTP ports. To use a HTTP/S server, provide a `proxy` option to SMTP configuration with the HTTP proxy configuration URL.
210
-
211
- ```javascript
212
- var smtpConfig = {
213
- host: 'smtp.gmail.com',
214
- port: 465,
215
- ...,
216
- //proxy config
217
- // assumes a HTTP proxy running on port 3128
218
- proxy: 'http://localhost:3128/'
219
- };
220
- ```
221
-
222
- Possible protocol values for the HTTP proxy:
223
-
224
- * `'http:'` if the proxy is running in a plaintext server
225
- * `'https:'` if the proxy is running in a secure server
226
-
227
- > NB! Proxy protocol (http/s) does not affect how SMTP connection is secured or not
228
-
229
- See an example of using a HTTP proxy [here](examples/proxy/http-proxy.js).
230
-
231
- #### SOCKS 4/5
232
-
233
- To use a HTTP/S server, provide a `proxy` option to SMTP configuration with the SOCKS4/5 proxy configuration URL.
234
-
235
- ```javascript
236
- var smtpConfig = {
237
- host: 'smtp.gmail.com',
238
- port: 465,
239
- ...,
240
- //proxy config
241
- // assumes a SOCKS5 proxy running on port 1080
242
- proxy: 'socks5://localhost:1080/'
243
- };
244
- ```
245
-
246
- > **NB!** When using SOCKS4, only an ipv4 address can be used
247
-
248
- Possible protocol values for the SOCKS proxy:
249
-
250
- * `'socks4:'` or `'socks4a:'` for a SOCKS4 proxy
251
- * `'socks5:'` or `'socks:'` for a SOCKS5 proxy
252
-
253
- See an example of using a SOCKS proxy [here](examples/proxy/socks-proxy.js).
254
-
255
- #### Custom connection handler
256
-
257
- If you do not want to use SOCKS or HTTP proxies then you can alternatively provide a custom
258
- proxy handling code with the `getSocket` method. In this case you should initiate a new
259
- socket yourself and pass it to Nodemailer for usage.
260
-
261
- ```javascript
262
- // This method is called every time Nodemailer needs a new
263
- // connection against the SMTP server
264
- transporter.getSocket = function(options, callback){
265
- getProxySocketSomehow(options.port, options.host, function(err, socket){
266
- if(err){
267
- return callback(err);
268
- }
269
- callback(null, {
270
- connection: socket
271
- });
272
- });
273
- };
274
- ```
275
-
276
- Normally proxies provide plaintext sockets, so if the connection is supposed to use TLS
277
- then Nodemailer upgrades the socket from plaintext to TLS itself. If the socket is
278
- already upgraded then you can pass additional option `secured: true` to prevent Nodemailer
279
- from upgrading the already upgraded socket.
280
-
281
- ```javascript
282
- callback(null, {
283
- connection: socket,
284
- secured: true
285
- });
286
- ```
287
-
288
- See complete example using a custom socket connector [here](examples/proxy/custom-proxy.js).
289
-
290
- ### Events
291
-
292
- #### Event:'idle'
293
-
294
- Applies to pooled SMTP connections. Emitted by the transport object if connection pool has free connection slots. Check if a connection is still available with `isIdle()` method (returns `true` if a connection is still available). This allows to create push-like senders where messages are not queued into memory in a Node.js process but pushed and loaded through an external queue like RabbitMQ.
295
-
296
- ```javascript
297
- var messages = [...'list of messages'];
298
- transporter.on('idle', function(){
299
- // send next messages from the pending queue
300
- while(transporter.isIdle() && messages.length){
301
- transporter.send(messages.shift());
302
- }
303
- });
304
- ```
305
-
306
- ### Authentication
307
-
308
- If authentication data is not present, the connection is considered authenticated from the start. Set authentication data with `options.auth`
309
-
310
- - **auth** is the authentication object
311
- - **auth.user** is the username
312
- - **auth.pass** is the password for the user
313
- - **auth.xoauth2** is the OAuth2 access token (preferred if both `pass` and `xoauth2` values are set) or an [XOAuth2](https://github.com/andris9/xoauth2) token generator object.
314
-
315
- **Using OAuth2**
316
-
317
- If a [XOAuth2](https://github.com/andris9/xoauth2) token generator is used as the value for `auth.xoauth2` then you do not need to set the value for `user` or `pass`. XOAuth2 generator generates required `accessToken` itself if it is missing or expired. In this case if the authentication fails, a new token is requested and the authentication is retried once. If it still fails, an error is returned.
318
-
319
- > **NB!** The correct OAuth2 scope for Gmail is `https://mail.google.com/`
320
-
321
- Install xoauth2 module to use XOauth2 token generators (not included by default)
322
-
323
- npm install xoauth2 --save
324
-
325
- **Example**
326
-
327
- ```javascript
328
- var nodemailer = require('nodemailer');
329
- var xoauth2 = require('xoauth2');
330
-
331
- // listen for token updates (if refreshToken is set)
332
- // you probably want to store these to a db
333
- generator.on('token', function(token){
334
- console.log('New token for %s: %s', token.user, token.accessToken);
335
- });
336
-
337
- // login
338
- var transporter = nodemailer.createTransport({
339
- service: 'gmail',
340
- auth: {
341
- xoauth2: xoauth2.createXOAuth2Generator({
342
- user: '{username}',
343
- clientId: '{Client ID}',
344
- clientSecret: '{Client Secret}',
345
- refreshToken: '{refresh-token}',
346
- accessToken: '{cached access token}'
347
- })
348
- }
349
- });
350
- ```
351
-
352
- ### Using *well-known* services
353
-
354
- If you do not want to specify the hostname, port and security settings for a well known service, you can use it by its name (case insensitive)
355
-
356
- ```javascript
357
- smtpTransport({
358
- service: 'gmail',
359
- auth: ..
360
- });
361
- ```
362
-
363
- See the list of all supported services [here](https://github.com/andris9/nodemailer-wellknown#supported-services).
364
-
365
- ## Verify SMTP connection configuration
366
-
367
- You can verify your SMTP configuration with `verify(callback)` call (also works as a Promise). If it returns an error, then something is not correct, otherwise the server is ready to accept messages.
368
-
369
- ```javascript
370
- // verify connection configuration
371
- transporter.verify(function(error, success) {
372
- if (error) {
373
- console.log(error);
374
- } else {
375
- console.log('Server is ready to take our messages');
376
- }
377
- });
378
- ```
379
-
380
- ## Send using a transport plugin
381
-
382
- In addition to SMTP you can use other kind of transports as well with Nodemailer. See *Available Transports* below for known transports.
383
-
384
- The following example uses [nodemailer-ses-transport](https://github.com/andris9/nodemailer-ses-transport) (Amazon SES).
385
-
386
- ```javascript
387
- var nodemailer = require('nodemailer');
388
- var ses = require('nodemailer-ses-transport');
389
- var transporter = nodemailer.createTransport(ses({
390
- accessKeyId: 'AWSACCESSKEY',
391
- secretAccessKey: 'AWS/Secret/key'
392
- }));
393
- ```
394
-
395
- If the transport plugin follows common conventions, then you can also load it dynamically with the `transport` option. This way you would not have to load the transport plugin in your code (you do need to install the transport plugin though before you can use it), you only need to modify the configuration data accordingly.
396
-
397
- ```javascript
398
- var nodemailer = require('nodemailer');
399
- var transporter = nodemailer.createTransport({
400
- transport: 'ses', // loads nodemailer-ses-transport
401
- accessKeyId: 'AWSACCESSKEY',
402
- secretAccessKey: 'AWS/Secret/key'
403
- });
404
- ```
405
-
406
- **Available Transports**
407
-
408
- - **[nodemailer-mandrill-transport](https://github.com/rebelmail/nodemailer-mandrill-transport)** for sending messages through Mandrill's Web API
409
- - **[nodemailer-pickup-transport](https://github.com/andris9/nodemailer-pickup-transport)** for storing messages to pickup folders
410
- - **[nodemailer-sailthru-transport](https://github.com/rebelmail/nodemailer-sailthru-transport)** for sending messages through Sailthru's Web API
411
- - **[nodemailer-sendgrid-transport](https://github.com/sendgrid/nodemailer-sendgrid-transport)** for sending messages through SendGrid's Web API
412
- - **[nodemailer-sendmail-transport](https://github.com/andris9/nodemailer-sendmail-transport)** for piping messages to the _sendmail_ command
413
- - **[nodemailer-ses-transport](https://github.com/andris9/nodemailer-ses-transport)** for sending messages to AWS SES
414
- - **[nodemailer-sparkpost-transport](https://github.com/sparkpost/nodemailer-sparkpost-transport)** for sending messages through SparkPost's Web API
415
- - **[nodemailer-stub-transport](https://github.com/andris9/nodemailer-stub-transport)** is just for returning messages, most probably for testing purposes
416
- - **[nodemailer-wellknown](https://github.com/nodemailer/nodemailer-wellknown)** for sending messages through one of those many [supported services](https://github.com/nodemailer/nodemailer-wellknown#supported-services)
417
- - **[nodemailer-postmark-transport](https://github.com/killmenot/nodemailer-postmark-transport)** for sending messages through Postmark's Web API
418
- - _add yours_ (see transport api documentation [here](#transports))
419
-
420
- # Sending mail
421
- Once you have a transporter object you can send mail with it:
422
-
423
- ```javascript
424
- transporter.sendMail(data[, callback])
425
- ```
426
-
427
- Where
428
- - **data** defines the mail content (see [e-mail message fields](#e-mail-message-fields) below)
429
- - **callback** is an optional callback function to run once the message is delivered or it failed
430
- - **err** is the error object if message failed
431
- - **info** includes the result, the exact format depends on the transport mechanism used
432
- - **info.messageId** most transports _should_ return the final Message-Id value used with this property
433
- - **info.envelope** includes the envelope object for the message
434
- - **info.accepted** is an array returned by SMTP transports (includes recipient addresses that were accepted by the server)
435
- - **info.rejected** is an array returned by SMTP transports (includes recipient addresses that were rejected by the server)
436
- - **info.pending** is an array returned by Direct SMTP transport. Includes recipient addresses that were temporarily rejected together with the server response
437
- - **info.response** is a string returned by SMTP transports and includes the last SMTP response from the server
438
-
439
- > If the message includes several recipients then the message is considered sent if at least one recipient is accepted
440
-
441
- If `callback` argument is not set then the method returns a Promise object. Nodemailer itself does not use Promises internally but it wraps the return into a Promise for convenience.
442
-
443
- ## E-mail message fields
444
- The following are the possible fields of an e-mail message:
445
-
446
- Commmon fields:
447
-
448
- - **from** - The e-mail address of the sender. All e-mail addresses can be plain `'sender@server.com'` or formatted `'"Sender Name" <sender@server.com>'`, see [Address Formatting](#address-formatting) for details
449
- - **to** - Comma separated list or an array of recipients e-mail addresses that will appear on the _To:_ field
450
- - **cc** - Comma separated list or an array of recipients e-mail addresses that will appear on the _Cc:_ field
451
- - **bcc** - Comma separated list or an array of recipients e-mail addresses that will appear on the _Bcc:_ field
452
- - **subject** - The subject of the e-mail
453
- - **text** - The plaintext version of the message as an Unicode string, Buffer, Stream or an attachment-like object (`{path: '/var/data/...'}`)
454
- - **html** - The HTML version of the message as an Unicode string, Buffer, Stream or an attachment-like object (`{path: 'http://...'}`)
455
- - **attachments** - An array of attachment objects (see [below](#attachments) for details)
456
-
457
- Advanced fields:
458
-
459
- - **sender** - An e-mail address that will appear on the _Sender:_ field (always prefer `from` if you're not sure which one to use)
460
- - **replyTo** - An e-mail address that will appear on the _Reply-To:_ field
461
- - **inReplyTo** - The message-id this message is replying to
462
- - **references** - Message-id list (an array or space separated string)
463
- - **watchHtml** - Apple Watch specific HTML version of the message. Same usage as with `text` or `html`
464
- - **icalEvent** – iCalendar event to use as an alternative. Same usage as with `text` or `html`. Additionally you could set `method` property (defaults to `'PUBLISH'`). See an example [here](examples/ical-event.js)
465
- - **priority** - Sets message importance headers, either `'high'`, `'normal'` (default) or `'low'`.
466
- - **headers** - An object or array of additional header fields (e.g. _{"X-Key-Name": "key value"}_ or _[{key: "X-Key-Name", value: "val1"}, {key: "X-Key-Name", value: "val2"}]_)
467
- - **alternatives** - An array of alternative text contents (in addition to text and html parts) (see [below](#alternatives) for details)
468
- - **envelope** - optional SMTP envelope, if auto generated envelope is not suitable (see [below](#smtp-envelope) for details)
469
- - **messageId** - optional Message-Id value, random value will be generated if not set
470
- - **date** - optional Date value, current UTC string will be used if not set
471
- - **encoding** - identifies encoding for text/html strings (defaults to 'utf-8', other values are 'hex' and 'base64')
472
- - **raw** - existing MIME message to use instead of generating a new one. If this value is set then you should also set the envelope object (if required) as the provided raw message is not parsed. The value could be a string, a buffer, a stream or an attachment-like object.
473
- - **textEncoding** - force content-transfer-encoding for text values (either *quoted-printable* or *base64*). By default the best option is detected (for lots of ascii use *quoted-printable*, otherwise *base64*)
474
- - **list** - helper for setting List-\* headers
475
-
476
- All text fields (e-mail addresses, plaintext body, html body, attachment filenames) use UTF-8 as the encoding. Attachments are streamed as binary.
477
-
478
- > **NB!** When using readable streams as any kind of content and sending fails then Nodemailer does not abort the already opened but not yet finished stream automatically, you need to do this yourself
479
-
480
- ```javascript
481
- var htmlstream = fs.createReadStream('content.html');
482
- transport.sendMail({html: htmlstream}, function(err){
483
- if(err){
484
- // check if htmlstream is still open and close it to clean up
485
- }
486
- });
487
- ```
488
-
489
- ## Attachments
490
- Attachment object consists of the following properties:
491
-
492
- - **filename** - filename to be reported as the name of the attached file, use of unicode is allowed. If you do not want to use a filename, set this value as `false`, otherwise a filename is generated automatically
493
- - **content** - String, Buffer or a Stream contents for the attachment
494
- - **path** - path to a file or an URL (data uris are allowed as well) if you want to stream the file instead of including it (better for larger attachments)
495
- - **contentType** - optional content type for the attachment, if not set will be derived from the `filename` property
496
- - **contentDisposition** - optional content disposition type for the attachment, defaults to 'attachment'
497
- - **cid** - optional content id for using inline images in HTML message source
498
- - **encoding** - If set and `content` is string, then encodes the content to a Buffer using the specified encoding. Example values: `base64`, `hex`, `binary` etc. Useful if you want to use binary attachments in a JSON formatted e-mail object.
499
- - **headers** - custom headers for the attachment node. Same usage as with message headers
500
- - **raw** - is an optional special value that overrides entire contents of current mime node including mime headers. Useful if you want to prepare node contents yourself
501
-
502
- Attachments can be added as many as you want.
503
-
504
- **Example**
505
-
506
- ```javascript
507
- var mailOptions = {
508
- ...
509
- attachments: [
510
- { // utf-8 string as an attachment
511
- filename: 'text1.txt',
512
- content: 'hello world!'
513
- },
514
- { // binary buffer as an attachment
515
- filename: 'text2.txt',
516
- content: new Buffer('hello world!','utf-8')
517
- },
518
- { // file on disk as an attachment
519
- filename: 'text3.txt',
520
- path: '/path/to/file.txt' // stream this file
521
- },
522
- { // filename and content type is derived from path
523
- path: '/path/to/file.txt'
524
- },
525
- { // stream as an attachment
526
- filename: 'text4.txt',
527
- content: fs.createReadStream('file.txt')
528
- },
529
- { // define custom content type for the attachment
530
- filename: 'text.bin',
531
- content: 'hello world!',
532
- contentType: 'text/plain'
533
- },
534
- { // use URL as an attachment
535
- filename: 'license.txt',
536
- path: 'https://raw.github.com/nodemailer/nodemailer/master/LICENSE'
537
- },
538
- { // encoded string as an attachment
539
- filename: 'text1.txt',
540
- content: 'aGVsbG8gd29ybGQh',
541
- encoding: 'base64'
542
- },
543
- { // data uri as an attachment
544
- path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
545
- }
546
- ]
547
- }
548
- ```
549
-
550
- ## Alternatives
551
- In addition to text and HTML, any kind of data can be inserted as an alternative content of the main body - for example a word processing document with the same text as in the HTML field. It is the job of the e-mail client to select and show the best fitting alternative to the reader. Usually this field is used for calendar events and such.
552
-
553
- Alternative objects use the same options as [attachment objects](#attachments). The difference between an attachment and an alternative is the fact that attachments are placed into _multipart/mixed_ or _multipart/related_ parts of the message white alternatives are placed into _multipart/alternative_ part.
554
-
555
- **Usage example:**
556
-
557
- ```javascript
558
- var mailOptions = {
559
- ...
560
- html: '<b>Hello world!</b>',
561
- alternatives: [
562
- {
563
- contentType: 'text/x-web-markdown',
564
- content: '**Hello world!**'
565
- }
566
- ]
567
- }
568
- ```
569
-
570
- Alternatives can be added as many as you want.
571
-
572
- ## Headers
573
-
574
- Most messages do not need any kind of tampering with the headers. If you do need to add custom headers either to the message or to an attachment/alternative, you can add these values with the `headers` option. Values are processed automatically, non-ascii strings are encoded as mime-words and long lines are folded.
575
-
576
- ```javascript
577
- var mail = {
578
- ...,
579
- headers: {
580
- 'x-my-key': 'header value',
581
- 'x-another-key': 'another value'
582
- }
583
- }
584
-
585
- // X-My-Key: header value
586
- // X-Another-Key: another value
587
- ```
588
-
589
- ### Multiple rows
590
-
591
- The same header key can be used multiple times if the header value is an Array
592
-
593
- ```javascript
594
- var mail = {
595
- ...,
596
- headers: {
597
- 'x-my-key': [
598
- 'value for row 1',
599
- 'value for row 2',
600
- 'value for row 3'
601
- ]
602
- }
603
- }
604
-
605
- // X-My-Key: value for row 1
606
- // X-My-Key: value for row 2
607
- // X-My-Key: value for row 3
608
- ```
609
-
610
- ### Prepared headers
611
-
612
- Normally all headers are encoded and folded to meet the requirement of having plain-ASCII messages with lines no longer than 78 bytes. Sometimes it is preferable to not modify header values and pass these as provided. This can be achieved with the `prepared` option:
613
-
614
- ```javascript
615
- var mail = {
616
- ...,
617
- headers: {
618
- 'x-processed': 'a really long header or value with non-ascii characters 👮',
619
- 'x-unprocessed': {
620
- prepared: true,
621
- value: 'a really long header or value with non-ascii characters 👮'
622
- }
623
- }
624
- }
625
-
626
- // X-Processed: a really long header or value with non-ascii characters
627
- // =?UTF-8?Q?=F0=9F=91=AE?=
628
- // X-Unprocessed: a really long header or value with non-ascii characters 👮
629
- ```
630
-
631
- ## Address Formatting
632
- All the e-mail addresses can be plain e-mail addresses
633
-
634
- ```
635
- foobar@blurdybloop.com
636
- ```
637
-
638
- or with formatted name (includes unicode support)
639
-
640
- ```
641
- "Ноде Майлер" <foobar@blurdybloop.com>
642
- ```
643
-
644
- > Notice that all address fields (even `from:`) are comma separated lists, so if you want to use a comma in the name part, make sure you enclose the name in double quotes: `"Майлер, Ноде" <foobar@blurdybloop.com>`
645
-
646
- or as an address object (in this case you do not need to worry about the formatting, no need to use quotes etc.)
647
-
648
- ```
649
- {
650
- name: 'Майлер, Ноде',
651
- address: 'foobar@blurdybloop.com'
652
- }
653
- ```
654
-
655
- All address fields accept comma separated list of e-mails or an array of e-mails or an array of comma separated list of e-mails or address objects - use it as you like. Formatting can be mixed.
656
-
657
- ```
658
- ...,
659
- to: 'foobar@blurdybloop.com, "Ноде Майлер" <bar@blurdybloop.com>, "Name, User" <baz@blurdybloop.com>',
660
- cc: ['foobar@blurdybloop.com', '"Ноде Майлер" <bar@blurdybloop.com>, "Name, User" <baz@blurdybloop.com>'],
661
- bcc: ['foobar@blurdybloop.com', {name: 'Майлер, Ноде', address: 'foobar@blurdybloop.com'}]
662
- ...
663
- ```
664
-
665
- You can even use unicode domains, these are automatically converted to punycode
666
-
667
- ```
668
- '"Unicode Domain" <info@müriaad-polüteism.info>'
669
- ```
670
-
671
- ## SMTP envelope
672
- SMTP envelope is usually auto generated from `from`, `to`, `cc` and `bcc` fields but if for some reason you want to specify it yourself (custom envelopes are usually used for VERP addresses), you can do it with `envelope` property.
673
-
674
- `envelope` is an object with the following params: `from`, `to`, `cc` and `bcc` just like with regular mail options. You can also use the regular address format, unicode domains etc.
675
-
676
- ```javascript
677
- mailOptions = {
678
- ...,
679
- from: 'mailer@kreata.ee', // listed in rfc822 message header
680
- to: 'daemon@kreata.ee', // listed in rfc822 message header
681
- envelope: {
682
- from: '"Daemon" <deamon@kreata.ee>', // used as MAIL FROM: address for SMTP
683
- to: 'mailer@kreata.ee, "Mailer" <mailer2@kreata.ee>' // used as RCPT TO: address for SMTP
684
- }
685
- }
686
- ```
687
-
688
- > Not all transports can use the `envelope` object, for example SES ignores it and only uses the data from the From:, To: etc. headers.
689
-
690
- ## Using Embedded Images
691
- Attachments can be used as embedded images in the HTML body. To use this feature, you need to set additional property of the attachment - `cid` (unique identifier of the file) which is a reference to the attachment file. The same `cid` value must be used as the image URL in HTML (using `cid:` as the URL protocol, see example below).
692
-
693
- **NB!** the cid value should be as unique as possible!
694
-
695
- ```javascript
696
- var mailOptions = {
697
- ...
698
- html: 'Embedded image: <img src="cid:unique@kreata.ee"/>',
699
- attachments: [{
700
- filename: 'image.png',
701
- path: '/path/to/file',
702
- cid: 'unique@kreata.ee' //same cid value as in the html img src
703
- }]
704
- }
705
- ```
706
-
707
- ## Using templates
708
-
709
- Nodemailer allows to use simple built-in templating or alternatively external renderers for common message types.
710
-
711
- ```javascript
712
- var transporter = nodemailer.createTransport(...);
713
- var send = transporter.templateSender(templates, [defaults]);
714
-
715
- // send a message based on provided templates
716
- send(mailData, context, callback);
717
- // or
718
- send(mailData, context).then(...).catch(...);
719
- ```
720
-
721
- Where
722
-
723
- * **templates** is an object with template strings for built-in renderer or an [EmailTemplate](https://github.com/niftylettuce/node-email-templates) object for more complex rendering
724
-
725
- ```javascript
726
- // built-in renderer
727
- var send = transporter.templateSender({
728
- subject: 'This template is used for the "subject" field',
729
- text: 'This template is used for the "text" field',
730
- html: 'This template is used for the "html" field'
731
- });
732
- // external renderer
733
- var EmailTemplate = require('email-templates').EmailTemplate;
734
- var send = transporter.templateSender(new EmailTemplate('template/directory'));
735
- ```
736
-
737
- * **defaults** is an optional object of message data fields that are set for every message sent using this sender
738
- * **mailData** includes message fields for current message
739
- * **context** is an object with template replacements, where `key` replaces `{{key}}` when using the built-in renderer
740
-
741
- ```javascript
742
- var templates = {
743
- text: 'Hello {{username}}!'
744
- };
745
- var context = {
746
- username: 'User Name'
747
- };
748
- // results in "Hello, User Name!" as the text body
749
- // of the message when using built-in renderer
750
- ```
751
-
752
- * **callback** is the `transporter.sendMail` callback (if not set then the function returns a Promise)
753
-
754
- > **NB!** If using built-in renderer then template variables are HTML escaped for the `html` field but kept as is for other fields
755
-
756
- **Example 1. Built-in renderer**
757
-
758
- ```javascript
759
- var transporter = nodemailer.createTransport('smtps://user%40gmail.com:pass@smtp.gmail.com');
760
-
761
- // create template based sender function
762
- var sendPwdReset = transporter.templateSender({
763
- subject: 'Password reset for {{username}}!',
764
- text: 'Hello, {{username}}, Please go here to reset your password: {{ reset }}',
765
- html: '<b>Hello, <strong>{{username}}</strong>, Please <a href="{{ reset }}">go here to reset your password</a>: {{ reset }}</p>'
766
- }, {
767
- from: 'sender@example.com',
768
- });
769
-
770
- // use template based sender to send a message
771
- sendPwdReset({
772
- to: 'receiver@example.com'
773
- }, {
774
- username: 'Node Mailer',
775
- reset: 'https://www.example.com/reset?token=<unique-single-use-token>'
776
- }, function(err, info){
777
- if(err){
778
- console.log('Error');
779
- }else{
780
- console.log('Password reset sent');
781
- }
782
- });
783
- ```
784
-
785
- **Example 2. External renderer**
786
-
787
- ```javascript
788
- var EmailTemplate = require('email-templates').EmailTemplate;
789
- var transporter = nodemailer.createTransport('smtps://user%40gmail.com:pass@smtp.gmail.com');
790
-
791
- // create template based sender function
792
- // assumes text.{ext} and html.{ext} in template/directory
793
- var sendPwdReminder = transporter.templateSender(new EmailTemplate('template/directory'), {
794
- from: 'sender@example.com',
795
- });
796
-
797
- // use template based sender to send a message
798
- sendPwdReminder({
799
- to: 'receiver@example.com',
800
- // EmailTemplate renders html and text but no subject so we need to
801
- // set it manually either here or in the defaults section of templateSender()
802
- subject: 'Password reminder'
803
- }, {
804
- username: 'Node Mailer',
805
- password: '!"\'<>&some-thing'
806
- }, function(err, info){
807
- if(err){
808
- console.log('Error');
809
- }else{
810
- console.log('Password reminder sent');
811
- }
812
- });
813
- ```
814
-
815
- ### Custom renderer
816
-
817
- In addition to the built-in and node-email-templates based renderers you can also bring your own.
818
-
819
- ```javascript
820
- var sendPwdReminder = transporter.templateSender({
821
- render: function(context, callback){
822
- callback(null, {
823
- html: 'rendered html content',
824
- text: 'rendered text content'
825
- });
826
- }
827
- });
828
- ```
829
-
830
- **Example. Using swig-email-templates**
831
-
832
- ```javascript
833
- var EmailTemplates = require('swig-email-templates');
834
- var transporter = nodemailer.createTransport('smtps://user%40gmail.com:pass@smtp.gmail.com');
835
-
836
- // create template renderer
837
- var templates = new EmailTemplates();
838
-
839
- // provide custom rendering function
840
- var sendPwdReminder = transporter.templateSender({
841
- render: function(context, callback){
842
- templates.render('pwreminder.html', context, function (err, html, text) {
843
- if(err){
844
- return callback(err);
845
- }
846
- callback(null, {
847
- html: html,
848
- text: text
849
- });
850
- });
851
- }
852
- });
853
- ...
854
- ```
855
-
856
- ## List-\* headers
857
-
858
- Nodemailer includes a helper for setting more complex List-\* headers with ease.
859
- Use message option `list` to provide all list headers. You do not need to add protocol
860
- prefix for the urls, or enclose the url between &lt; and &gt;, this is handled automatically.
861
-
862
- If the value is a string, it is treated as an URL. If you want to provide an optional comment,
863
- use `{url:'url', comment: 'comment'}` object. If you want to have multiple header rows for the
864
- same List-\* key, use an array as the value for this key. If you want to have multiple URLs for
865
- single List-\* header row, use an array inside an array.
866
-
867
- > List-\* headers are treated as pregenerated values, this means that lines are not folded and strings
868
- are not encoded. Use only ascii characters and be prepared for longer header lines.
869
-
870
- ```javascript
871
- var mailOptions = {
872
- list: {
873
- // List-Help: <mailto:admin@example.com?subject=help>
874
- help: 'admin@example.com?subject=help',
875
- // List-Unsubscribe: <http://example.com> (Comment)
876
- unsubscribe: {
877
- url: 'http://example.com',
878
- comment: 'Comment'
879
- },
880
- // List-Subscribe: <mailto:admin@example.com?subject=subscribe>
881
- // List-Subscribe: <http://example.com> (Subscribe)
882
- subscribe: [
883
- 'admin@example.com?subject=subscribe',
884
- {
885
- url: 'http://example.com',
886
- comment: 'Subscribe'
887
- }
888
- ],
889
- // List-Post: <http://example.com/post>, <mailto:admin@example.com?subject=post> (Post)
890
- post: [
891
- [
892
- 'http://example.com/post',
893
- {
894
- url: 'admin@example.com?subject=post',
895
- comment: 'Post'
896
- }
897
- ]
898
- ]
899
- }
900
- };
901
- ```
902
-
903
- # Available Plugins
904
-
905
- In addition to built-in e-mail fields you can extend these by using plugins.
906
-
907
- - **[nodemailer-markdown](https://github.com/andris9/nodemailer-markdown)** to use markdown for the content
908
- - **[nodemailer-dkim](https://github.com/andris9/nodemailer-dkim)** to sign messages with DKIM
909
- - **[nodemailer-html-to-text](https://github.com/andris9/nodemailer-html-to-text)** to auto generate plaintext content from html
910
- - **[nodemailer-express-handlebars](https://github.com/yads/nodemailer-express-handlebars)** to auto generate html emails from handlebars/mustache templates
911
- - **[nodemailer-plugin-inline-base64](https://github.com/mixmaxhq/nodemailer-plugin-inline-base64)** to convert base64 images to attachments
912
- - **[nodemailer-hashcash](https://github.com/andris9/nodemailer-hashcash)** to generate [hashcash](http://www.hashcash.org/) headers
913
- - _add yours_ (see plugin api documentation [here](#plugin-api))
914
-
915
- # Using Gmail
916
- Even though Gmail is the fastest way to get started with sending emails, it is by no means a preferable solution unless you are using OAuth2 authentication. Gmail expects the user to be an actual user not a robot so it runs a lot of heuristics for every login attempt and blocks anything that looks suspicious to defend the user from account hijacking attempts. For example you might run into trouble if your server is in another geographical location – everything works in your dev machine but messages are blocked in production.
917
-
918
- Additionally Gmail has came up with the concept of ['less secure'](https://support.google.com/accounts/answer/6010255?hl=en) apps which is basically anyone who uses plain password to login to Gmail, so you might end up in a situation where one username can send (support for 'less secure' apps is enabled) but other is blocked (support for 'less secure' apps is disabled). When using this method make sure to enable the required functionality by completing the "[captcha enable](https://accounts.google.com/b/0/displayunlockcaptcha)". Without this, less secure connections won't work.
919
-
920
- To prevent having login issues you should either use XOAUTH2 (see details [here](https://github.com/nodemailer/nodemailer-smtp-transport#authentication)) or use another provider and preferably a dedicated one like [Mailgun](http://www.mailgun.com/) or [SendGrid](http://mbsy.co/sendgrid/12237825) or any other. Usually these providers have free plans available that are comparable to the daily sending limits of Gmail. Gmail has a limit of 500 recipients a day (a message with one _To_ and one _Cc_ address counts as two messages since it has two recipients) for @gmail.com addresses and 2000 for Google Apps customers, larger SMTP providers usually offer about 200-300 recipients a day for free.
921
-
922
- # Delivering Bulk Mail
923
- Here are some tips how to handle bulk mail, for example if you need to send 10 million messages at once (originally published as a [blog post](http://www.andrisreinman.com/delivering-bulk-mail-with-nodemailer/)).
924
- 1. **Use a dedicated SMTP provider** like [SendGrid](http://mbsy.co/sendgrid/12237825) or [Mailgun](http://www.mailgun.com/) or any other. Do not use services that offer SMTP as a sideline or for free (that's Gmail or the SMTP of your homepage hosting company) to send bulk mail – you'll hit all the hard limits immediatelly or get labelled as spam. Basically you get what you pay for and if you pay zero then your deliverability is near zero as well. E-mail might seem free but it is only free to a certain amount and that amount certainly does not include 10 million e-mails in a short period of time.
925
- 2. **Use a dedicated queue manager,** for example [RabbitMQ](http://www.rabbitmq.com/) for queueing the e-mails. Nodemailer creates a callback function with related scopes etc. for every message so it might be hard on memory if you pile up the data for 10 million messages at once. Better to take the data from a queue when there's a free spot in the connection pool (previously sent message returns its callback). See [rabbit-queue](examples/rabbit-queue) for an example of using RabbitMQ queues with Nodemailer connection pool.
926
- 3. **Use [nodemailer-smtp-pool](https://github.com/nodemailer/nodemailer-smtp-pool) transport.** You do not want to have the overhead of creating a new connection and doing the SMTP handshake dance for every single e-mail. Pooled connections make it possible to bring this overhead to a minimum.
927
- 4. **Set `maxMessages` option to `Infinity`** for the nodemailer-smtp-pool transport. Dedicated SMTP providers happily accept all your e-mails as long you are paying for these, so no need to disconnect in the middle if everything is going smoothly. The default value is 100 which means that once a connection is used to send 100 messages it is removed from the pool and a new connection is created.
928
- 5. **Set `maxConnections` to whatever your system can handle.** There might be limits to this on the receiving side, so do not set it to `Infinity`, even 20 is probably much better than the default 5. A larger number means a larger amount of messages are sent in parallel.
929
- 6. **Use file paths not URLs for attachments.** If you are reading the same file from the disk several million times, the contents for the file probably get cached somewhere between your app and the physical hard disk, so you get your files back quicker (assuming you send the same attachment to all recipients). There is nothing like this for URLs – every new message makes a fresh HTTP fetch to receive the file from the server.
930
- 7. If the SMTP service accepts HTTP API as well you still might prefer SMTP and not the HTTP API as HTTP introduces additional overhead. You probably want to use HTTP over SMTP if the HTTP API is bulk aware – you send a message template and the list of 10 million recipients and the service compiles this information into e-mails itself, you can't beat this with SMTP.
931
-
932
- # Implementing plugins and transports
933
-
934
- There are 3 stages a plugin can hook to
935
- 1. **'compile'** is the step where e-mail data is set but nothing has been done with it yet. At this step you can modify mail options, for example modify `html` content, add new headers etc. Example: [nodemailer-markdown](https://github.com/andris9/nodemailer-markdown) that allows you to use `markdown` source instead of `text` and `html`.
936
- 2. **'stream'** is the step where message tree has been compiled and is ready to be streamed. At this step you can modify the generated MIME tree or add a transform stream that the generated raw e-mail will be piped through before passed to the transport object. Example: [nodemailer-dkim](https://github.com/andris9/nodemailer-dkim) that adds DKIM signature to the generated message.
937
- 3. **Transport** step where the raw e-mail is streamed to destination. Example: [nodemailer-smtp-transport](https://github.com/nodemailer/nodemailer-smtp-transport) that streams the message to a SMTP server.
938
-
939
- ## Including plugins
940
- 'compile' and 'stream' plugins can be attached with `use(plugin)` method
941
-
942
- ```javascript
943
- transporter.use(step, pluginFunc)
944
- ```
945
-
946
- Where
947
- - **transporter** is a transport object created with `createTransport`
948
- - **step** is a string, either 'compile' or 'stream' that defines when the plugin should be hooked
949
- - **pluginFunc** is a function that takes two arguments: the mail object and a callback function
950
-
951
- # Plugin API
952
- All plugins (including transports) get two arguments, the mail object and a callback function.
953
-
954
- Mail object that is passed to the plugin function as the first argument is an object with the following properties:
955
- - **data** is the mail data object that is passed to the `sendMail` method
956
- - **message** is the [BuildMail](https://github.com/nodemailer/buildmail) object of the message. This is available for the 'stream' step and for the transport but not for 'compile'.
957
- - **resolveContent** is a helper function for converting Nodemailer compatible stream objects into Strings or Buffers
958
-
959
- ## resolveContent()
960
- If your plugin needs to get the full value of a param, for example the String value for the `html` content, you can use `resolveContent()` to convert Nodemailer compatible content objects to Strings or Buffers.
961
-
962
- ```javascript
963
- data.resolveContent(obj, key, callback)
964
- ```
965
-
966
- Where
967
- - **obj** is an object that has a property you want to convert to a String or a Buffer
968
- - **key** is the name of the property you want to convert
969
- - **callback** is the callback function with (err, value) where `value` is either a String or Buffer, depending on the input
970
-
971
- **Example**
972
-
973
- ```javascript
974
- function plugin(mail, callback){
975
- // if mail.data.html is a file or an url, it is returned as a Buffer
976
- mail.resolveContent(mail.data, 'html', function(err, html){
977
- if(err){
978
- return callback(err);
979
- }
980
- console.log('HTML contents: %s', html.toString());
981
- callback();
982
- });
983
- };
984
- ```
985
-
986
- ## 'compile'
987
- Compile step plugins get only the `mail.data` object but not `mail.message` in the `mail` argument of the plugin function. If you need to access the `mail.message` as well use 'stream' step instead.
988
-
989
- This is really straightforward, your plugin can modify the `mail.data` object at will and once everything is finished run the callback function. If the callback gets an error object as an argument, then the process is terminated and the error is returned to the `sendMail` callback.
990
-
991
- **Example**
992
-
993
- The following plugin checks if `text` value is set and if not converts `html` value to `text` by removing all html tags.
994
-
995
- ```javascript
996
- transporter.use('compile', function(mail, callback){
997
- if(!mail.text && mail.html){
998
- mail.text = mail.html.replace(/<[^>]*>/g, ' ');
999
- }
1000
- callback();
1001
- });
1002
- ```
1003
-
1004
- See [plugin-compile.js](examples/plugin-compile.js) for a working example.
1005
-
1006
- ## 'stream'
1007
- Streaming step is invoked once the message structure is built and ready to be streamed to the transport. Plugin function still gets `mail.data` but it is included just for the reference, modifying it should not change anything (unless the transport requires something from the `mail.data`, for example `mail.data.envelope`).
1008
-
1009
- You can modify the `mail.message` object as you like, the message is not yet streaming anything (message starts streaming when the transport calls `mail.message.createReadStream()`).
1010
-
1011
- In most cases you might be interested in the [message.transform()](https://github.com/nodemailer/buildmail#transform) method for applying transform streams to the raw message.
1012
-
1013
- **Example**
1014
-
1015
- The following plugin replaces all tabs with spaces in the raw message.
1016
-
1017
- ```javascript
1018
- var transformer = new (require('stream').Transform)();
1019
- transformer._transform = function(chunk, encoding, done) {
1020
- // replace all tabs with spaces in the stream chunk
1021
- for(var i = 0; i < chunk.length; i++){
1022
- if(chunk[i] === 0x09){
1023
- chunk[i] = 0x20;
1024
- }
1025
- }
1026
- this.push(chunk);
1027
- done();
1028
- };
1029
-
1030
- transporter.use('stream', function(mail, callback){
1031
- // apply output transformer to the raw message stream
1032
- mail.message.transform(transformer);
1033
- callback();
1034
- });
1035
- ```
1036
-
1037
- See [plugin-stream.js](examples/plugin-stream.js) for a working example.
1038
-
1039
- Additionally you might be interested in the [message.getAddresses()](https://github.com/nodemailer/buildmail#getaddresses) method that returns the contents for all address fields as structured objects.
1040
-
1041
- **Example**
1042
-
1043
- The following plugin prints address information to console.
1044
-
1045
- ```javascript
1046
- transporter.use('stream', function(mail, callback){
1047
- var addresses = mail.message.getAddresses();
1048
- console.log('From: %s', JSON.stringify(addresses.from));
1049
- console.log('To: %s', JSON.stringify(addresses.to));
1050
- console.log('Cc: %s', JSON.stringify(addresses.cc));
1051
- console.log('Bcc: %s', JSON.stringify(addresses.bcc));
1052
- callback();
1053
- });
1054
- ```
1055
-
1056
- ## Transports
1057
- Transports are objects that have a method `send` and properies `name` and `version`. Additionally, if the transport object is an Event Emitter, 'log' events are piped through Nodemailer. A transport object is passed to the `nodemailer.createTransport(transport)` method to create the transporter object.
1058
-
1059
- **`transport.name`**
1060
-
1061
- This is the name of the transport object. For example 'SMTP' or 'SES' etc.
1062
-
1063
- ```javascript
1064
- transport.name = require('package.json').name;
1065
- ```
1066
-
1067
- **`transport.version`**
1068
-
1069
- This should be the transport module version. For example '0.1.0'.
1070
-
1071
- ```javascript
1072
- transport.version = require('package.json').version;
1073
- ```
1074
-
1075
- **`transport.send(mail, callback)`**
1076
-
1077
- This is the method that actually sends out e-mails. The method is basically the same as 'stream' plugin functions. It gets two arguments: `mail` and a callback. To start streaming the message, create the stream with `mail.message.createReadStream()`
1078
-
1079
- Callback function should return an `info` object as the second arugment. This info object should contain `messageId` value with the Message-Id header (without the surrounding < > brackets)
1080
-
1081
- The following example pipes the raw stream to the console.
1082
-
1083
- ```javascript
1084
- transport.send = function(mail, callback){
1085
- var input = mail.message.createReadStream();
1086
- var messageId = (mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, '');
1087
- input.pipe(process.stdout);
1088
- input.on('end', function() {
1089
- callback(null, {
1090
- messageId: messageId
1091
- });
1092
- });
1093
- };
1094
- ```
1095
-
1096
- **`transport.close(args*)`**
1097
-
1098
- If your transport needs to be closed explicitly, you can implement a `close` method.
1099
-
1100
- This is purely optional feature and only makes sense in special contexts (eg. closing a SMTP pool).
1101
-
1102
- **`transport.isIdle()`**
1103
-
1104
- If your transport is able to notify about idling state by issuing `'idle'` events then this method should return if the transport is still idling or not.
1105
-
1106
- **Wrapping up**
1107
-
1108
- Once you have a transport object, you can create a mail transporter out of it.
1109
-
1110
- ```
1111
- var nodemailer = require('nodemailer');
1112
- var transport = require('some-transport-method');
1113
- var transporter = nodemailer.createTransport(transport);
1114
- transporter.sendMail({mail data});
1115
- ```
1116
-
1117
- See [minimal-transport.js](examples/minimal-transport.js) for a working example.
1118
-
1119
- # License
1120
- **Nodemailer** is licensed under [MIT license](https://github.com/nodemailer/nodemailer/blob/master/LICENSE). Basically you can do whatever you want to with it
11
+ For an upgraded and up to date **Nodemailer PRO** see [nodemailer.com](https://nodemailer.com/) homepage.
1121
12
 
1122
13
  --------------------------------------------------------------------------------
1123
14
 
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "nodemailer",
3
- "version": "2.6.3",
3
+ "version": "2.7.2",
4
4
  "description": "Easy as cake e-mail sending from your Node.js applications",
5
5
  "main": "lib/nodemailer.js",
6
6
  "homepage": "https://nodemailer.com/",
7
7
  "scripts": {
8
8
  "test": "grunt mochaTest"
9
9
  },
10
- "repository" :
11
- { "type" : "git"
12
- , "url" : "https://nodemailer.com/.git"
13
- },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://nodemailer.com/"
13
+ },
14
14
  "keywords": [
15
15
  "e-mail",
16
16
  "mime",
@@ -24,10 +24,10 @@
24
24
  "license": "MIT",
25
25
  "bugs": {
26
26
  "url": "https://github.com/nodemailer/nodemailer/issues"
27
- },
27
+ },
28
28
  "dependencies": {
29
- "libmime": "2.1.0",
30
- "mailcomposer": "3.12.0",
29
+ "libmime": "3.0.0",
30
+ "mailcomposer": "4.0.1",
31
31
  "nodemailer-direct-transport": "3.3.2",
32
32
  "nodemailer-shared": "1.1.0",
33
33
  "nodemailer-smtp-pool": "2.8.2",
@@ -37,20 +37,20 @@
37
37
  "devDependencies": {
38
38
  "amqp": "^0.2.6",
39
39
  "chai": "^3.5.0",
40
- "email-templates": "^2.4.1",
40
+ "email-templates": "^2.5.4",
41
41
  "grunt": "^1.0.1",
42
42
  "grunt-cli": "^1.2.0",
43
43
  "grunt-eslint": "^19.0.0",
44
- "grunt-mocha-test": "^0.12.7",
45
- "handlebars": "^4.0.5",
46
- "mocha": "^3.0.2",
44
+ "grunt-mocha-test": "^0.13.2",
45
+ "handlebars": "^4.0.6",
46
+ "mocha": "^3.2.0",
47
47
  "nodemailer-dkim": "^1.0.4",
48
- "nodemailer-markdown": "^1.0.0",
48
+ "nodemailer-markdown": "^1.0.1",
49
49
  "nodemailer-stub-transport": "^1.1.0",
50
50
  "proxy-test-server": "^1.0.0",
51
- "sinon": "^1.17.5",
52
- "smtp-server": "^1.14.2",
53
- "swig-email-templates": "^3.0.0"
51
+ "sinon": "^1.17.6",
52
+ "smtp-server": "^1.16.1",
53
+ "swig-email-templates": "^4.0.0"
54
54
  },
55
55
  "engines": {
56
56
  "node": ">=0.10.0"