-
-
Save fredyjohn/982771 to your computer and use it in GitHub Desktop.
simple sendmail for node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Simple Sendmail | |
* Changes : | |
* - Added base64 encoding to username and password | |
* - Handling a simple attachment ( single base64 encoded attachment ) | |
*/ | |
var net = require('net') | |
, config = { | |
type: 'text/plain', | |
boundary: "boundaryseparator" | |
} | |
exports.send = function(options, cb) { | |
var stream = net.createConnection(options.port, options.host) | |
var from = options.from.match(/(<)(.*)(>)/) | |
? options.from.match(/(<)(.*)(>)/)[2] | |
: options.from | |
var to = options.to.match(/(<)(.*)(>)/) | |
? options.to.match(/(<)(.*)(>)/)[2] | |
: options.to | |
stream.on('connect', function() { | |
var out = [ | |
'ehlo ' + (options.domain || from.split('@')[1]) | |
, 'auth login' | |
, new Buffer(options.username,'utf-8').toString('base64') | |
, new Buffer(options.password,'utf-8').toString('base64') | |
, 'mail from:<' + from + '>' | |
, 'rcpt to:<' + to + '>' | |
, 'data' | |
, 'From: ' + options.from | |
, 'To: ' + options.to | |
, 'Date: ' + new Date().toUTCString() | |
, 'Subject: ' + options.subject | |
, 'MIME-Version: 1.0' | |
, 'Content-Type: multipart/mixed;boundary="'+config.boundary+'"' | |
, '--'+config.boundary | |
, 'Content-Type: ' + (options.type || config.type) | |
, '' | |
, options.body | |
.split(/\r\n|\n|\r/) | |
.join('\r\n') | |
.replace('\r\n.\r\n', '\r\n. \r\n') | |
, '--'+config.boundary | |
, 'Content-Type: application/octet-stream' | |
, 'Content-Transfer-Encoding: Base64' | |
, 'Content-Disposition: attachment;filename="'+options.attachment_name+'"' | |
, '' | |
, options.attachment_data | |
, '' | |
, '--'+config.boundary+'--' | |
, '.' | |
, 'quit' | |
] | |
//TODO: Remove delays in stream write ( reason for the send mailer code failing some time ) | |
for(var i=0; i<out.length; i++) | |
{ | |
stream.write(out[i]+'\r\n','ascii') | |
cb && cb(out[i]) | |
} | |
stream.end() | |
}) | |
stream.on('error', function(err) { | |
cb && cb(err) | |
}) | |
stream.on('data', function (data) { | |
cb && cb(data.toString('utf-8')) | |
}) | |
stream.on('end', function() { | |
cb && cb() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment