forked from nodemailer/nodemailer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.js
563 lines (481 loc) · 16.7 KB
/
mail.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
var mimelib = require("mimelib-noiconv"),
util = require("util"),
EventEmitter = require("events").EventEmitter,
fs = require("fs");
/*
* Load all engines, assuming each .js file in the root of the engines
* directory is an engine. To avoid collisions, dependencies should be
* stored in a directory of the same name as the engine.
*/
var engines = {};
fs.readdirSync(__dirname + '/engines').forEach(function(engine) {
if(/\.js$/.test(engine)) {
var engineName = engine.replace(/\.js$/, "");
//Load the engine into the engine object
engines[engineName] = require(__dirname + '/engines/' + engine);
}
});
/*
* Version constants
*/
var X_MAILER_NAME = "Nodemailer",
X_MAILER_VERSION = "0.1.24; +http://www.nodemailer.org";
/**
* mail
*
* Provides an API to send e-mails with Node.js through a SMTP server.
* This API is unicode friendly, you don't have to escape non-ascii chars.
*
* NB! Before sending any e-mails, update mail.SMTP with correct values
*
**/
// EXPOSE TO THE WORLD
exports.CommonServers = {
gmail:[],
yahoo:[],
hotmail:[]
};
// Expose EmailMessage for the world
exports.EmailMessage = EmailMessage;
/**
* mail.send_mail(params, callback) -> undefined
* - params (Object): e-mail data
* - callback (Function): will be run after completion
*
* Shortcut function to send e-mails. See EmailMessage for param structure
**/
exports.send_mail = function(params, callback){
var em = new EmailMessage(params);
em.send(callback);
return em;
};
var gencounter = 0,
instancecounter = 0;
/**
* new mail.EmailMessage(params)
* - params (Object): message data (can be altered afterwards)
*
* Creates an object to send an e-mail.
*
* params can hold the following data
*
* - **server** server to send message to (will default to exports.SMTP)
* - **sender** e-mail address of the sender
* - **headers** an object with custom headers.
* `{"X-Myparam": "test", "Message-ID":"12345"}`
* - **to** comma separated list of TO: addressees
* - **cc** comma separated list of CC: addressees
* - **bcc** comma separated list of BCC: addressees
* - **reply_to** A reply-to address
* - **subject** Message subject
* - **body** Message body in plain text
* - **html** Message body in HTML format
* - **attachments** an array of attachements of {filename, contents, cid}
* filename (mandatory) is a String, contents can be String or Buffer,
* cid is optional.
*
* - **debug** if set, outputs the whole communication of SMTP server to console
*
* All the params can be edited/added after defining the object
*
* Events:
* forward(oldAddr,newAddr) - was told to try new address by server.
* defer(addr) - server takes responsibility for delivery.
* retain(addr) - unable to send to mailbox.
* Usage:
* var em = EmailMessage();
* em.sender = '"Andris Reinman" <andris@node.ee>'
* em.to = 'andris@kreata.ee'
* em.body = "Hello world!";
* em.send(function(error, success){});
*
* NB! mail.SMTP needs to be set before sending any e-mails!
**/
function EmailMessage(params){
EventEmitter.call(this);
params = params || {};
this.SERVER = params.server || exports.SMTP;
this.sender = params.sender;
this.headers = params.headers || {};
this.to = params.to;
this.cc = params.cc;
this.bcc = params.bcc;
this.reply_to = params.reply_to;
this.subject = params.subject || "";
this.body = params.body || "";
this.html = params.html;
this.attachments = params.attachments || [];
this.debug = !!params.debug;
this.charset = params.charset || "UTF-8";
this.encoding = params.encoding || "quoted-printable";
this.callback = null;
}
var utillib = require("util");
util.inherits(EmailMessage,EventEmitter);
/**
* mail.EmailMessage#prepareVariables() -> undefined
*
* Prepares some needed variables
**/
EmailMessage.prototype.prepareVariables = function(){
if(this.html || this.attachments.length){
this.content_multipart = true;
this.content_mixed = !!this.attachments.length;
//'=_' is not valid quoted printable
//'?' is not in any known base64 extension
this.content_boundary = "----NODEMAILER-?=_"+(++gencounter)+"-"+Date.now();
// defaults to multipart/mixed but if there's attachments with cid value set
// use multipart/related - mail clients hide the duplicates this way
var mixed = "mixed";
for(var i=0, len=this.attachments.length; i<len;i++){
if(this.attachments[i].cid){
mixed = "related";
break;
}
}
this.content_type = "multipart/"+(this.content_mixed?mixed:"alternative")+
"; boundary=\""+this.content_boundary+"\"";
}else{
this.content_multipart = false;
this.content_type = "text/plain; charset="+this.charset;
this.content_transfer_encoding = this.encoding; // Changed from quoted-printable; 5/23/2011.
}
}
/**
* mail.EmailMessage#generateHeaders() -> String
*
* Generates a header string where lines are separated by \r\n
**/
EmailMessage.prototype.generateHeaders = function(){
var headers = [];
// Mime
headers.push([
"X-Mailer",
X_MAILER_NAME+" ("+X_MAILER_VERSION+")"
].join(": "));
// add custom
var keys = Object.keys(this.headers);
for(var i=0, len=keys.length; i<len; i++){
headers.push([
upperFirst(keys[i].trim()),
this.headers[keys[i]]
].join(": "));
}
// Date
var date = new Date;
headers.push([
upperFirst("Date"),
date.toGMTString()
].join(": "));
// From
var from = this.generateAddresses(this.sender,1, "fromAddress");
if(from.length){
headers.push([
upperFirst("From"),
from
].join(": "));
}
// To
var to = this.generateAddresses(this.to, 0, "toAddress");
if(to.length){
headers.push([
upperFirst("To"),
to
].join(": "));
}
// CC
var cc = this.generateAddresses(this.cc, 0, "toAddress");
if(cc.length){
headers.push([
upperFirst("Cc"),
cc
].join(": "));
}
// BCC
var bcc = this.generateAddresses(this.bcc, 0, "toAddress");
if(exports.sendmail && bcc.length){
headers.push([
upperFirst("Bcc"),
bcc
].join(": "));
}
//Reply-To
var reply_to = this.generateAddresses(this.reply_to, 1);
if(reply_to.length){
headers.push([
upperFirst("Reply-To"),
reply_to
].join(": "));
}
// Subject
headers.push([
upperFirst("Subject"),
this.subject && (hasUTFChars(this.subject) &&
mimelib.encodeMimeWord(this.subject, "Q") || this.subject) || ''
].join(": "));
// Mime
headers.push([
"MIME-Version",
"1.0"
].join(": "));
// Content-type
headers.push([
"Content-Type",
this.content_type
].join(": "));
if(!this.content_multipart){
headers.push([
"Content-Transfer-Encoding",
this.content_transfer_encoding
].join(": "));
}
// output
return headers.map(function(elm){
return mimelib.foldLine(elm);
}).join("\r\n");
}
/**
* mail.EmailMessage#generateBody() -> String
*
* Generates a body string. If this is a multipart message then different
* parts will be separated by boundary, body+html are put into separate
* multipart/alternate block
**/
EmailMessage.prototype.generateBody = function(){
if(!this.content_multipart){
return this.body && mimelib.encodeQuotedPrintable(this.body) || "";
}
var body_boundary = this.content_mixed?
"----NODEMAILER-?=_"+(++gencounter)+"-"+Date.now():
this.content_boundary,
rows = [];
if(this.content_mixed){
rows.push("--"+this.content_boundary);
rows.push("Content-Type: multipart/alternative; boundary=\""+body_boundary+"\"");
rows.push("");
}
if(!this.body.trim() && this.html){
this.body = stripHTML(this.html);
}
// body
rows.push("--"+body_boundary);
rows.push("Content-Type: text/plain; charset="+this.charset);
rows.push("Content-Transfer-Encoding: "+this.encoding); // Changed from quoted-printable; 5/23/2011.
rows.push("");
// dots in the beginning of the lines will be replaced with double dots
rows.push(mimelib.encodeQuotedPrintable(this.body.trim()).replace(/^\./gm,'..'));
rows.push("");
// html
if(this.html){
rows.push("--"+body_boundary);
rows.push("Content-Type: text/html; charset="+this.charset);
rows.push("Content-Transfer-Encoding: "+this.encoding); // Changed from quoted-printable; 5/23/2011.
rows.push("");
rows.push(mimelib.encodeQuotedPrintable(this.html.trim()).replace(/^\./gm,'..'));
rows.push("");
}
if(this.content_mixed){
rows.push("--"+body_boundary+"--");
}
// attachments
var current;
for(var i=0; i<this.attachments.length; i++){
current = {
filename: hasUTFChars(this.attachments[i].filename)?
mimelib.encodeMimeWord(this.attachments[i].filename, "Q"):
this.attachments[i].filename.replace(/"/g,''),
mime_type: getMimeType(this.attachments[i].filename),
contents: this.attachments[i].contents instanceof Buffer?
this.attachments[i].contents:
new Buffer(this.attachments[i].contents, "utf-8"),
disposition: "attachment",
content_id: this.attachments[i].cid || ((++gencounter)+"."+Date.now()+"@"+(this.SERVER.hostname || "localhost"))
};
rows.push("--"+this.content_boundary);
rows.push("Content-Type: "+current.mime_type+"; name=\""+current.filename+"\"");
rows.push("Content-Disposition: "+current.disposition+"; filename=\""+current.filename+"\"");
rows.push("Content-ID: <"+current.content_id+">");
rows.push("Content-Transfer-Encoding: base64");
rows.push("");
/* Changed to conform with RFC-2045 section 6.7. */
rows.push(current.contents.toString("base64").replace(/.{76}/g,"$&\r\n"));
}
rows.push("--"+this.content_boundary+"--");
return rows.join("\r\n");
}
/**
* mail.EmailMessage#generateAddresses(addresses, limit, use_list) -> String
* - addresses (String): Comma separated list of addresses
* - limit (String): How many addresses will be used from the list
* - use_list (String): property name where to add plain e-mail addresses
*
* Parses an address string, finds the data and normalizes it. If use_string
* is set, (ie. "toAddress") then found e-mail addresses are appended to
* a list with the same name (this.toAddress). Plain e-mail addresses are
* needed for the SMTP server.
**/
EmailMessage.prototype.generateAddresses = function(addresses, limit, use_list){
var parsed, output = [], current;
limit = limit || 0;
try{
parsed = mimelib.parseAddresses(addresses);
}catch(E){parsed = [];}
var list = [];
for(var i=0; i<parsed.length; i++){
current = parsed[i];
current.address = current.address && current.address.trim();
if(!current.address)continue;
list.push(current.address);
if(hasUTFChars(current.address)){
current.address = mimelib.encodeMimeWord(current.address, "Q");
}
if(current.name){
current.name = upperFirst(current.name.trim(), true);
if(hasUTFChars(current.name)){
current.name = mimelib.encodeMimeWord(current.name, "Q");
}
current.name = '"' + current.name + '"';
current.address = '<' + current.address.trim() +'>';
output.push(current.name + " " +current.address);
}else{
output.push(current.address);
}
}
if(limit && output.length>limit){
output = output.slice(0, limit);
list = list.slice(0, limit);
}
if(use_list){
if(!this[use_list]){
this[use_list] = list;
}else{
this[use_list] = this[use_list].concat(list);
}
}
return output.join(", ");
}
/**
* mail.EmailMessage#send(callback) -> undefined
* - callback (Function): function to be called if sending succeedes or fails
*
* Generates a full message body and forwards it to the SMTP server.
* callback gets two params - error and success. If error is set, then
* something bad happened, if there's no error but success is false, then
* SMTP server failed and the message should be resent. If there's no error
* and success is true, then the message was sent to the recipients
**/
EmailMessage.prototype.send = function(callback){
var instanceId = ++instancecounter;
if(this.debug){
var str = X_MAILER_NAME+", "+X_MAILER_VERSION+", Node.js "+process.version+": "+instanceId;
console.log(str);
console.log(Array(str.length+1).join("=")+"\n");
}
//Use the engine configured by the user
for(var engine in engines) {
if(exports[engine]) {
exports[engine].instanceId = instanceId;
engines[engine].send(this, exports[engine], callback);
return;
}
}
}
/**
* getMimeType(filename) -> String
* - filename (String): Failinimi, mille mime tüüpi otsida
*
* Otsib välja faililaiendi alusel õige mime tüübi, vaikimisi
* kui tüüpi ei leita on application/octet-stream
**/
function getMimeType(filename){
var defaultMime = "application/octet-stream",
extension = filename && filename.substr(filename.lastIndexOf(".")+1).trim().toLowerCase();
return extension && mimelib.contentTypes[extension] || defaultMime;
}
/**
* upperFirst(str) -> String
* - str (String): string to be converted
*
* Converts first letters upper case, other lower case
*
* "x-name-value" -> "X-Name-Value"
*
**/
function upperFirst(str, keepUpper){
if(!keepUpper){
str = str.toLowerCase();
}
return str.replace(/^\s*[a-z]|[\-\s][a-z]/g,function(c){
return c.toUpperCase()
});
}
/**
* hasUTFChars(str) -> Boolean
* - str (String): String to be checked for non-ascii chars
*
* Tries to detect if a string has non-ascii characters. In this case the
* string needs to be encoded before sent to the SMTP server
**/
function hasUTFChars(str){
var rforeign = /[^\u0000-\u007f]/;
return !!rforeign.test(str);
}
/**
* stripHTML(str) -> String
* - str (String): HTML string to be converted
*
* Converts a HTML string into plain text
**/
function stripHTML(str){
if(!str)return str;
str = str instanceof Buffer ? str.toString("utf-8"):str;
str = str.replace(/\r?\n/g," ");
str = str.replace(/<(?:\/p|br|\/tr|\/table|\/div)>/g,"\n");
// hide newlines with two 00 chars (enables multiline matches)
str = str.replace(/\r?\n/g,"-\u0000\u0000-");
// H1-H6, add underline
str = str.replace(/<[hH]\d[^>]*>(.*?)<\/[hH]\d[^>]*>/g,function(a,b){
var line = "";
b = b.replace(/<[^>]*>/g," ");
b = b.replace(/\s\s+/g," ");
b = b.trim();
if(!b)
return "";
for(var i=0, len = b.length; i<len; i++){
line+="-";
}
return b+"\n"+line+"\n\n";
});
// LI, indent by 2 spaces + *
str = str.replace(/<li[^>]*>(.*?)<\/?(?:li|ol|ul)[^>]*>/ig,function(a,b){
b = b.replace(/<[^>]*>/g," ");
b = b.replace(/\s\s+/g," ");
b = b.trim();
if(!b)
return "";
return "-®®®®-* "+b+"\n";
});
// PRE, indent by 4 spaces
str = str.replace(/<pre[^>]*>(.*?)<\/pre[^>]*>/ig,function(a,b){
b = b.replace(/<[^>]*>/g," ");
b = b.replace(/\s\s+/g," ");
b = b.trim();
if(!b)
return "";
b = b.replace(/[ \t]*\n[ \t]*/g,"\n-®®®®--®®®®-");
return "\n-®®®®--®®®®-"+b.trim()+"\n\n";
});
// restore
str = str.replace(/\s*-\u0000\u0000-\s*/g,"\n");
// remove all remaining html tags
str = str.replace(/<[^>]*>/g," ");
// remove duplicate spaces
str = str.replace(/[ ][ ]+/g," ");
// remove spaces before and after newlines
str = str.replace(/[ \t]*\n[ \t]*/g,"\n");
// remove more than 2 newlines in a row
str = str.replace(/\n\n+/g,"\n\n");
// restore hidden spaces (four (r) signs for two spaces)
str = str.replace(/-®®®®-/g," ");
return str.trim();
}