Created
April 10, 2013 19:53
-
-
Save cgkio/5357881 to your computer and use it in GitHub Desktop.
Parse inbound emails with Node.js, Cradle, and CouchDB
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
// Required modules. | |
var cradle = require('cradle'); | |
var util = require('util'); | |
var http = require('http'); | |
// Config. | |
var config = require('./config'); | |
// Variable to hold chunked data from Postmark. | |
var mailRaw = ''; | |
// Create a new HTTP server to accept Postmark POSTs. | |
http.createServer(function(req, res) { | |
req.on('data', function(chunk) { | |
mailRaw += chunk; | |
}); | |
req.on('end', function() { | |
// Get the JSON payload from Postmark. | |
var mailJSON = JSON.parse(mailRaw); | |
// Transform attachments (fairly cheesy, but seems to work). | |
if(mailJSON.Attachments.length) { | |
var couchAttachments = '{'; | |
for(var i=0; i<mailJSON.Attachments.length; i++) { | |
couchAttachments += '"' + mailJSON.Attachments[i].Name + '": {'; | |
couchAttachments += '"content_type":"' + mailJSON.Attachments[i].ContentType + '",'; | |
couchAttachments += '"data":"' + mailJSON.Attachments[i].Content + '"'; | |
couchAttachments += '},'; | |
} | |
couchAttachments = couchAttachments.substring(0, (couchAttachments.length)-1); | |
couchAttachments += '}'; | |
var _attachments = JSON.parse(couchAttachments); | |
// Replace old attachments property with new Couchified attachments. | |
mailJSON._attachments = _attachments; | |
delete mailJSON.Attachments; | |
} | |
// Connect to CouchDB instance. | |
var db = new (cradle.Connection)(config.couchHost, config.couchPort, { | |
auth : { | |
username : config.couchUserName, | |
password : config.couchPassword | |
} | |
}).database(config.couchDatabase); | |
// Insert new document. | |
db.save(mailJSON.MessageID, mailJSON, function (err, res) { | |
if(err) { | |
util.puts('Error! Could not save mailRaw. ' + err.reason); | |
} | |
else { | |
util.puts('Saved document with id: ' + res.id); | |
} | |
}); | |
// Reset our holder variable. | |
mailRaw = ''; | |
// Send an empty response. | |
res.end(); | |
}); | |
}).listen(config.serverPort); |
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
module.exports = { | |
serverPort: 8000, | |
couchHost: '127.0.0.1', | |
couchPort: 5984, | |
couchUserName: '', | |
couchPassword: '', | |
couchDatabase: 'couchmail' | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment