Project: Wakanda
Code Location: git://github.com/Wakanda/waf-mail.gitmaster
Browse
/
Outline
Download File
SMTP.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
/* Copyright (c) 4D, 2011
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

// SMTP library. 
//
// Usage:
//
//		There are two ways to use this library. You can either create an SMTP object and connect it to a SMTP
//		server. This is the more versatile way. As it will allow you to send several emails, and disconnecting 
//		when done. Or you can use the send() function, which will do everything necessary to connect and submit
//		a message to a SMTP server. All callbacks have same first two arguments: a boolean telling if operation
//		was successful followed by an array of line(s) containing the actual reply by the SMTP server. Additional
//		arguments may follow.
//		
//		If you need more control (and are familiar with SMTP protocol), use the SMTPClient low-level library.

function SMTPScope () {

	var DEFAULT_PORT			= 25;

	var STATES = {
		
		NOT_CONNECTED:			1,	// State just after creation.
		IDLE:					2,	// Connected to SMTP server, awaiting commands.
		STARTTLS:               3,  // Upgrading to SSL.
		AUTHENTIFICATION:		4,	// Authentification.
		SENDING_MAIL:			5,	// Sending an email.
		TERMINATED:				6,	// Has sent QUIT command.

		CONNECTION_BROKEN:		-1,	// Connection has been lost.
			
	};

	var	isWakanda			= typeof requireNative != 'undefined';
		
	var validEmailRegExp	= /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/;
	
	var mail;
	var smtp;			
	var threeDigitReply;

	if (isWakanda) {

		smtp = require('waf-mail/smtpClient');
		threeDigitReply = require('waf-mail/threeDigitReply');
		mail = require('waf-mail/mail');

	} else {

		smtp = require('./smtpClient.js');
		threeDigitReply = require('./threeDigitReply.js');
		mail = require('./mail.js');

	}
	
	// Exception for SMTP, see codes below.
	
	var SMTPException  = function (code) {
	
		this.code = code;
	
	}
	SMTPException.INVALID_STATE		= -1;	// Command or operation can't be performed in current state.
	SMTPException.INVALID_ARGUMENT	= -2;	// At least an argument is wrong.
	SMTPException.NO_AUTH_LOGIN		= -3;	// SMTP server doesn't support "AUTH LOGIN".
	
	// If arguments are given, connect to server on creation.	

	function SMTP (address, port, isSSL, domain, callback) {
				
		var state		= STATES.NOT_CONNECTED;
		var smtpClient	= new smtp.SMTPClient();
		
		var nonSSLDomain, is8BitMIME, supportBDAT;
		
		this.SMTPException = SMTPException;
		
		// Connect to a SMTP server. All arguments except callback are mandatory. Note that some SMTP servers require 
		// domain to be specified, you may use an empty string if not needed. Callback has an additional third boolean
		// argument, indicating if the connected server is ESMTP, and a fourth, an array of lines, containing the
		// extensions if any. connect() function will always try to use the EHLO command before HELO.
		
		this.connect = function (address, port, isSSL, domain, callback) {
		
			if (state != STATES.NOT_CONNECTED) 
		
				throw new SMTPException(SMTPException.INVALID_STATE);
						
			if (typeof address != 'string' || typeof port == 'undefined' || typeof isSSL == 'undefined' 
			|| typeof domain != 'string')
				
				throw new SMTPException(SMTPException.INVALID_ARGUMENT);
		
			if (typeof port == 'string') 
				
				port = port.toNumber();
					
			else if (typeof port != 'number') {
				
				// Port must be a number.
		
				throw new SMTPException(SMTPException.INVALID_ARGUMENT);
				
			}			
			
			nonSSLDomain = domain;	// Save for later use.
				
			var	connectFunction = isSSL ? smtpClient.sslConnect : smtpClient.connect;
			
			connectFunction(address, port, function (reply, isProbableESMTP) {
			
				// If possible, use ESMTP.

				if (reply.isPositiveCompletion()) {
				
					var helloCommand;
								
					helloCommand = isProbableESMTP ? smtpClient.sendEHLO : smtpClient.sendHELO;
					helloCommand(domain, function (reply) {
					
						if (reply.isPositiveCompletion()) {
				
							state = STATES.IDLE;
							if (typeof callback == 'function') {
					
								if (helloCommand == smtpClient.sendEHLO)
								
									callback(true, reply.getLines(), true, smtpClient.getExtensions());
									
								else
								
									callback(true, reply.getLines(), false);
								
							}
					
						} else {
						
							// Try HELO command, not ESMTP.
							
							smtpClient.sendHELO(domain, function (reply) {

								state = STATES.IDLE;
								if (typeof callback == 'function')
					
									callback(reply.isPositiveCompletion(), reply.getLines(), false);
					
							});
						
						}

					});
					
				} else {
				
					// Error at greeting should not happen.
				
					if (typeof callback == 'function') 
					
						callback(false, reply.getLines());
					
				}

			});
			
		}
		
		var authenticateUser, authenticatePassword, authenticateCallback;
		
		var authenticateCompleteCallback = function (reply) {

			state = STATES.IDLE;
			if (typeof authenticateCallback == 'function')
				
				authenticateCallback(reply.isPositiveCompletion(), reply.getLines());				

		}

		var authenticatePasswordCallback = function (reply) {
		
			if (!reply.isPositiveIntermediate()) {
			
				state = STATES.IDLE;
				if (typeof authenticateCallback == 'function')
				
					authenticateCallback(false, reply.getLines());				
			
			} else
			
				smtpClient.sendRawCommand(authenticatePassword, authenticateCompleteCallback);
		
		}
		
		var authenticateUserCallback = function (reply) {
		
			if (!reply.isPositiveIntermediate()) {
			
				state = STATES.IDLE;
				if (typeof authenticateCallback == 'function')
				
					authenticateCallback(false, reply.getLines());				
			
			} else
			
				smtpClient.sendRawCommand(authenticateUser, authenticatePasswordCallback);
			
		}
				
		// Authenticate with SMTP. Currently only support "AUTH LOGIN" (username and password are sent using base64).
		// Caller is supposed to have checked that SMTP server support "AUTH LOGIN".
		
		this.authenticate = function (user, password, callback) {
	
			if (state != STATES.IDLE) 
		
				throw new SMTPException(SMTPException.INVALID_STATE);
		
			else if (typeof user != 'string' || typeof password != 'string') {
			
				// Invalid parameter.
				
				throw new SMTPException(SMTPException.INVALID_ARGUMENT);
			
			} else {
			
				authenticateUser = (new Buffer(user)).toString('base64');
				authenticatePassword = (new Buffer(password)).toString('base64');
				authenticateCallback = callback;
				
				state = STATES.AUTHENTIFICATION;
				smtpClient.sendRawCommand('AUTH LOGIN', authenticateUserCallback);
			
			}
		
		}
		
		// Issue the STARTTLS command, this will "upgrade" connection to secured.
		
		this.starttls = function (callback) {
		
			if (state != STATES.IDLE) 
		
				throw new SMTPException(SMTPException.INVALID_STATE);
				
			else {
			
			    state = STATES.STARTTLS;
				smtpClient.sendRawCommand('STARTTLS', function (reply) {
				
				    state = STATES.IDLE;
				    if (!reply.isPositiveCompletion()) {
				    
				        if (typeof callback == 'function')
				        
    				        callback(false, reply.getLines())
				        				    
				    } else {
					
						// Upgrade to SSL. Specification requests that a EHLO command is sent again.
						// Do so with domain used by initial EHLO (from server's greeting). Wait a 
						// few (100) milliseconds before doing so.
				    
				        smtpClient.getSocket().setSecure();
						setTimeout(function () {
					
							smtpClient.sendEHLO(nonSSLDomain, function (reply) {    
				        
				                if (typeof callback == 'function')
				        
    				                callback(reply.isPositiveCompletion(), reply.getLines())
				        		
				            });
				            
				        }, 100);
				        
                    }
				    
				});
				
			}
		
		}		
		
		var sendRecipients, sendRecipientsIndex, sendMail, sendCallback;
		
		// Used by both DATA and BDAT sending methods.
		
		var sendContentCompletionCallback = function (reply) {
		
			state = STATES.IDLE;
			if (typeof sendCallback == 'function') 
				
				sendCallback(reply.isPositiveCompletion(), reply.getLines());		
		
		}
		
		var sendContentCallback = function (reply) {
	
			if (!reply.isPositiveIntermediate()) {
			
				state = STATES.IDLE;
				if (typeof sendCallback == 'function') 
				
					sendCallback(false, reply.getLines());		
		
			} else {
			
				var	i;
								
				// Send header.
				
				var header	= sendMail.getHeader();
						
				for (i = 0; i < header.length; i++) {
				
					smtpClient.sendContent(header[i]);
					smtpClient.sendContent('\r\n');
					
				}
				
				// If not already done, set specified body type.
				// An empty line separates header and body.
				// If email uses MIME, add boundary before body.
								
				var bodyType	= sendMail.getBodyType();
				var mimeMessage	= sendMail.getMIMEMessage();
				
				if (mimeMessage != null) {
				
					smtpClient.sendContent('\r\n--' + mimeMessage.boundary + '\r\n');
					
					// If body type is unspecified, uses "text/stream".
					
					if (bodyType != null)
					
						smtpClient.sendContent('Content-Type: ' + bodyType + '\r\n\r\n');
						
					else
					
						smtpClient.sendContent('Content-Type: text/plain\r\n\r\n');

				} else {
				
					// Note that if 'Content-Type' has already been specified in the headers, 
					// this will add one more.
				
					if (bodyType != null)
					
						smtpClient.sendContent('Content-Type: ' + bodyType + '\r\n');
						
					smtpClient.sendContent('\r\n');
				
				}
				 
				// Send body if any.
				
				var body	= sendMail.getBody();
				
				for (i = 0; i < body.length; i++) {
				
					smtpClient.sendContent(body[i]);
					smtpClient.sendContent('\r\n');
				
				}
				
				// Send attachments if any.
					
				if (mimeMessage != null) {
				
					smtpClient.sendContent('\r\n');
				
					var	buffer = mimeMessage.toBuffer(is8BitMIME ? 1 : 0);
					
					smtpClient.sendContent(buffer);
				
				}
					
				// A single dot on a line terminates an email.				

				smtpClient.sendContentTerminator(sendContentCompletionCallback);
			
			}		
		
		}

		// Send header using BDAT command.
		
		var sendHeader = function () {
		
			var header			= sendMail.getHeader();
			var allocationSize	= 0;
						
			for (var i = 0; i < header.length; i++)
				
				allocationSize += (header[i].length + 1) * 2;	// Add two bytes for CRLF.
				
			var	buffer	= new Buffer(allocationSize);
			var	size	= 0;
						
			for (var i = 0; i < header.length; i++) {
				
				buffer.write(header[i], size);
				size += buffer._charsWritten;
				buffer.writeUInt16BE(0x0d0a, size);
				size += 2;
		
			}
			
			// Do not send header/body line break, sendBody() will do it.
			
			smtpClient.sendBDAT(buffer.slice(0, size), false, sendBody);
						
		}
		
		// Send body using BDAT command.
		
		var sendBody = function (reply) {

			if (!reply.isPositiveCompletion()) {
			
				state = STATES.IDLE;
				if (typeof sendCallback == 'function') 
				
					sendCallback(false, reply.getLines());		
		
			} else {

				var body			= sendMail.getBody();
				var allocationSize	= 0;
						
				for (var i = 0; i < body.length; i++)
				
					allocationSize += (body[i].length + 1) * 2;	// Add two bytes for CRLF.
			
				// Allocate buffer. And specify body type, see comments in sendContentCallback().
				
				var buffer;
				var bodyType	= sendMail.getBodyType();
				var mimeMessage	= sendMail.getMIMEMessage();
				var size		= 0;
								
				if (bodyType == null)
				
					buffer = new Buffer(allocationSize + 256);
					
				else
				
					buffer = new Buffer(allocationSize + bodyType.length * 2 + 128);
				
				if (mimeMessage != null) {
				
					buffer.write('\r\n--' + mimeMessage.boundary + '\r\n', size);
					size += buffer._charsWritten;
					
					if (bodyType != null)
					
						buffer.write('Content-Type: ' + bodyType + '\r\n\r\n', size);
						
					else
					
						buffer.write('Content-Type: text/plain\r\n\r\n', size);
						
					size += buffer._charsWritten;

				} else {
								
					if (bodyType != null) {
					
						buffer.write('Content-Type: ' + bodyType + '\r\n', size);
						size += buffer._charsWritten;
						
					}
					buffer.write('\r\n', size);
					size += buffer._charsWritten;
				
				}
				
				for (i = 0; i < body.length; i++) {
				
					buffer.write(body[i], size);
					size += buffer._charsWritten;
					buffer.writeUInt16BE(0x0d0a, size);
					size += 2;

				}
				
				if (mimeMessage != null) {
				
					buffer.writeUInt16BE(0x0d0a, size);
					size += 2;
					smtpClient.sendBDAT(buffer.slice(0, size), false, sendAttachments);
				
				} else 
				
					smtpClient.sendBDAT(buffer.slice(0, size), true, sendContentCompletionCallback);
					
			}
	
		}

		// Send attachments using BDAT command.
		
		var sendAttachments = function (reply) {

			if (!reply.isPositiveCompletion()) {
			
				state = STATES.IDLE;
				if (typeof sendCallback == 'function') 
				
					sendCallback(false, reply.getLines());		
		
			} else

				smtpClient.sendBDAT(sendMail.getMIMEMessage().toBuffer(1), true, sendContentCompletionCallback);

		}	
		
		var sendDataCallback = function (reply) {
		
			if (!reply.isPositiveCompletion()) {
			
				state = STATES.IDLE;
				if (typeof sendCallback == 'function') 
				
					sendCallback(false, reply.getLines());		
				
			} else if (supportBDAT)
			
				sendHeader();
			
			else
			
				smtpClient.sendDATA(sendContentCallback);

		}
		
		var sendRecipientCallback = function (reply) {
		
			if (!reply.isPositiveCompletion()) {
			
				state = STATES.IDLE;
				if (typeof sendCallback == 'function') 
				
					sendCallback(false, reply.getLines());		
		
			} else {
			
				var recipient, callback;
		
				recipient = sendRecipients[sendRecipientsIndex];
				callback = sendRecipientsIndex == sendRecipients.length - 1 ? sendDataCallback : sendRecipientCallback;
				sendRecipientsIndex++;
			
				smtpClient.sendRCPT('<' + recipient + '>', callback);
			
			}

		}
		
		var extractRecipients = function (email, name, resultArray) {
		
			var	r	= email.getField(name);

			if (typeof r == 'string')
			
				resultArray.push(r);
				
			else if (r instanceof Array) {
			
				var	i;
				
				for (i = 0; i < r.length; i++)
				
					resultArray.push(r[i]);
						
			}		
		
		}

		// Send an email. 
		//
		//	from:			the sender of email;
		//	recipients:		the recipient or an array of recipients (String), note "Cc" and "Bcc" are checked and 
		//					added to recipients;
		//	email:			a Mail object which is the mail to send, all its fields must have been set;
		//	callback:		called upon success or failure: first argument is true if successful, second
		//					argument is the lines of the last reply.
		
		this.send = function (from, recipients, email, callback) {

			if (state != STATES.IDLE)

				throw new SMTPException(SMTPException.INVALID_STATE);
								
			if (typeof from != 'string' 
			|| !(email instanceof mail.Mail)
			|| (typeof callback != 'function' && typeof callback != 'undefined'))
			
				throw new SMTPException(SMTPException.INVALID_ARGUMENT);
			
			if (typeof recipients == 'string') {
					
			    var	t = recipients;
					
			    recipients = new Array();
			    recipients.push(t);
					
			} else if (!(recipients instanceof Array)) {
			
				// If recipients is not an Array, create one.
			
				recipients = new Array();
				
			}
			
			// Add "Cc" and "Bcc" to recipients.
			
			extractRecipients(email, 'cc', recipients);
			extractRecipients(email, 'bcc', recipients);
			extractRecipients(email, 'Cc', recipients);
			extractRecipients(email, 'Bcc', recipients);
			
			// Add header fields for MIME attachments.
			
			var mimeMessage	= email.getMIMEMessage();
			
			if (mimeMessage != null) {

				// Make sure there is only one "Content-Type" field in header. 
				// Otherwise, some mail client may not decode message correctly as MIME multipart.

				for (var k in email) 
				
					if (typeof email[k] == 'string' && k.match(/^content\-type$/i) != null)
				
						delete email[k];
				
				// Add MIME version and "Content-Type" field.
			
				email.addField('MIME-Version', '1.0');
				email.addField('Content-Type', 'multipart/mixed; boundary="' + mimeMessage.boundary + '"');
			
			}
			
			// "Parse" recipients (check validity of emails).
			
			sendRecipients = new Array();
						
			for (var i = 0; i < recipients.length; i++) {
			
				if (typeof recipients[i] != 'string')

					continue;
					
				var	matchedEmail;
				
				if ((matchedEmail = recipients[i].match(validEmailRegExp)) == null || !matchedEmail.length)
				
					continue;
					
				sendRecipients.push(matchedEmail[0]);
	
			}			
						
			sendRecipientsIndex = 0;
			sendMail = email;
			sendCallback = callback;
			
			var extensions	= smtpClient.getExtensions();
			
			is8BitMIME = supportBDAT = false;
			if (typeof extensions == 'object' && extensions instanceof Array) {
			
				for (var i = 0; i < extensions.length; i++)  {
					
					if (extensions[i].search('8BITMIME') != -1)
					
						is8BitMIME = true;
						
					else if (extensions[i].search('CHUNKING') != - 1) 
					
						supportBDAT = true;					
					
				}
			
			}
			
			state = STATES.SENDING_MAIL;
			smtpClient.sendMAIL('<' + from + '>', is8BitMIME, sendRecipientCallback);
		
		}
				
		var forceClose = function () {
			
			state = STATES.TERMINATED;
			if (smtpClient != null) {
			
				smtpClient.forceClose();		
				smtpClient = null;

			}
		
		}
		this.forceClose = forceClose;
		
		// Send QUIT command, this is the proper way to disconnect from a SMTP server.
		
		this.quit = function (callback) {
		
			if (state != STATES.IDLE) 
			
				throw new SMTPException(SMTPException.INVALID_STATE);
				
			else {
			
				smtpClient.sendQUIT(function (reply) {
			
					forceClose();
					if (typeof callback == 'function') 
					
						callback(reply.isPositiveCompletion(), reply.getLines());

				});
			
			}
		
		}
		
		// If arguments are given, connect on creation.
			
		if (typeof address != 'undefined' && typeof port != 'undefined') 
			
			this.connect(address, port, isSSL, domain, callback);
		
	}
	
	return SMTP;

}

var SMTP	= SMTPScope();

// Create a new SMTP client.

var createClient = function (address, port, isSSL, domain, callback) {
	
	return new SMTP(address, port, isSSL, domain, callback);

}

// Submit (send) a mail to a SMTP server. All arguments are mandatory. Last argument can be a Mail object, with its 
// header (fields) and body filled. Or it can be a email addresses of sender and recipient, followed by subject and 
// message content. For Wakanda, this function is synchronous and return a status if successful.
//
// If the SMTP server is connected using a non SSL socket and supports STARTTLS, then the connection will be 
// automatically upgraded to SSL. This is better for security, of course. But in SSL mode, server will probably 
// support "AUTH LOGIN" (send username and password in base64 encoded form), whereas it may not in non secured 
// connections.
//
// The returned status has an isOk attribute telling if the command is successful or not. The action attribute tells
// more detail in case of failure. Attribute smtp.text (an Array of string(s)) and smtp.code attributes return the 
// last "three-digit" reply from server. See below for the constant definitions of the actions.

var	actionDoneSuccessful		= 0;
var	actionFailedToConnect		= 1;
var	actionFailedStartTLS		= 2;
var	actionFailedToAuthenticate	= 3;
var	actionUnableToAuthenticate	= 4;
var	actionFailedToSend			= 5;
var actionFailedToQuitProperly	= 6;

var send = function (address, port, isSSL, username, password, from, recipient, subject, content) {

	var	isWakanda	= typeof requireNative != 'undefined';	
	var smtp		= new SMTP();
	var	mail		= require(isWakanda ? 'waf-mail/mail' : './mail.js');
	var	status		= { action: -1, isOk: false, smtp: {} };

	if (typeof address != 'string' || typeof port != 'number' || typeof isSSL != 'boolean'
	|| typeof username != 'string' || typeof password != 'string') 

		throw new smtp.SMTPException(smtp.SMTPException.INVALID_ARGUMENT);
	
	// Accept both a mail object or "set" of arguments.
		  
	var email;
	
	if (arguments.length == 6)
	
		email = arguments[5];
				
	else if (typeof from != 'string' || (typeof recipient != 'string' && !(recipient instanceof Array))
	|| typeof subject != 'string' || typeof content != 'string')
		
		throw new smtp.SMTPException(smtp.SMTPException.INVALID_ARGUMENT);
		
	else
		
		email = mail.createMessage(from, recipient, subject, content);	
		
	// Event loop exit function. For wakanda, use exitWait() to get out of wait(). Otherwise, close SMTP client, this
	// will get out of event loop.
		
	var exit = function () {
	
		if (isWakanda)
		
			exitWait();
			
		else
		
			smtp.forceClose();
	
	}
	
	// Check extensions for STARTTLS.
	
	var supportSTARTTLS = function (extensions) {
	
		if (typeof extensions == 'undefined')
		
			return false;
			
		var	i;
		
		for (i = 0; i < extensions.length; i++) 
		
			if (extensions[i].match(/STARTTLS/) != null)
			
				return true;
	
		return false;
	}
	
	// Check for "AUTH LOGIN" support.

	var supportAUTH_LOGIN = function (extensions) {
	
		if (typeof extensions == 'undefined')
		
			return false;
			
		var	i;
		
		for (i = 0; i < extensions.length; i++) 
		
			if (extensions[i].match(/^AUTH/) != null && extensions[i].match(/LOGIN/) != null)
			
				return true;
	
		return false;
	}
	
	// Authenticate and send email.

	var authenticateAndSend = function () {
	
		smtp.authenticate(username, password, function (isOk, replyLines) {

			if (!isOk) {
			
				status.action = actionFailedToAuthenticate;
				status.isOk = isOk;
				status.smtp.text = replyLines;
				exit();

			} else {
			
				var	from, to;
				
				from = typeof email.From == 'string' ? email.From : email.from;
				to = typeof email.To != 'undefined' ? email.To : email.to;			// Can be a String or an array of String.
					 
				smtp.send(from, to, email, function (isOk, replyLines) {

					if (!isOk) {

						status.action = actionFailedToSend;
						status.isOk = isOk;
						status.smtp.text = replyLines;
						exit();
						
					} else

						smtp.quit(function (isOk, replyLines) {
						
							// Event if QUIT command is erroneous but send is successful, 
							// still consider that as a success.
							
							status.action = isOk ? actionDoneSuccessful : actionFailedToQuitProperly;
							status.isOk = true;
							status.smtp.text = replyLines;							
							exit();

						});
														
				});
				
			}
					
		});
		
	}
	
	smtp.connect(address, port, isSSL, '', function (isOk, replyLines, isESMTP, extensions) {
				 
		if (!isOk) {

			status.action = actionFailedToConnect;
			status.isOk = isOk;
			status.smtp.text = replyLines;		
			exit();
			
		} else if (isESMTP) {
		
			if (isSSL == false && supportSTARTTLS(extensions) && isWakanda) {
			
				// If non SSL connection and SMTP server supports STARTTLS, then upgrade to secured.
				
				smtp.starttls(function (isOk, replyLines) {
				
					if (!isOk) {

						status.action = actionFailedStartTLS;
						status.isOk = isOk;
						status.smtp.text = replyLines;					
						exit();

					} else

						authenticateAndSend();
				
				});			
			
			} else if (supportAUTH_LOGIN(extensions)) {
			
				// Usual case: sending on a secured or not connection.
			
				authenticateAndSend();			

			} else {
			
				// If no support for "AUTH LOGIN", we won't be able to authenticate, exit with error.
				
				status.action = actionUnableToAuthenticate;
				status.isOk = false;
				exit();
				throw new smtp.SMTPException(smtp.SMTPException.NO_AUTH_LOGIN);
			
			}
			
		} else {
		
			// Connected to non ESMTP server (is there still any around?).
			// Suppose that "AUTH LOGIN" is supported.
		
			authenticateAndSend();
		
		}
		
	});
			
	if (isWakanda) {
	
		// Asynchronous connection and sending.
	
		wait();
	
		// Force freeing of resources.
	
		smtp.forceClose();
		
	}
	
	// Retrieve the error code of last command reply from SMTP server.
	
	if (typeof status.smtp.text != 'undefined' && typeof status.smtp.text[0] == 'string')
	
		status.smtp.code = parseInt(status.smtp.text[0].substring(0, 3));
	
	return status;
	
}

// Here are the codes for the status.action attribute, they tell where the send() function failed.

send.ACTION_UNKNOWN					= -1;
send.ACTION_DONE_SUCCESSFUL			= actionDoneSuccessful;
send.ACTION_FAILED_TO_CONNECT		= actionFailedToConnect;
send.ACTION_FAILED_STARTTLS			= actionFailedStartTLS;
send.ACTION_FAILED_TO_AUTHENTICATE	= actionFailedToAuthenticate;
send.ACTION_UNABLE_TO_AUTHENTICATE 	= actionUnableToAuthenticate;
send.ACTION_FAILED_TO_SEND			= actionFailedToSend;
send.ACTION_QUIT_COMMAND_ERRONEOUS	= actionFailedToQuitProperly;

exports.createClient = createClient;
exports.send = send;
exports.SMTP = SMTP;