Created
September 30, 2014 12:54
-
-
Save Furzel/5f8d395215cd1f00b34a to your computer and use it in GitHub Desktop.
Post an email to Front public API
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
var https = require('https'), | |
url = require('url'); | |
// your credentials | |
var apiKey = '*** YOUR API KEY ***', | |
companySlug = '*** YOUR COMPANY SLUG ***'; | |
// Build the first request to retrieve all your inboxes | |
var listInboxesOptions = { | |
host: 'webhooks.frontapp.com', | |
path: '/api/1/inboxes', | |
auth: companySlug + ':' + apiKey, | |
method: 'GET' | |
}; | |
function getInboxList(done) { | |
var req = https.request(listInboxesOptions, function (res) { | |
if (res.statusCode !== 200) | |
return done('ERROR'); | |
var chunks = []; | |
res.on('data', function (chunk) { | |
chunks.push(new Buffer(chunk)); | |
}); | |
res.on('end', function() { | |
var body = Buffer.concat(chunks).toString(); | |
done(null, JSON.parse(body)); | |
}); | |
}); | |
req.end(); | |
} | |
// build the second request to post an email | |
var data = { | |
from: 'jhon.doe@somemail.com', | |
subject: 'test email', | |
text_body: 'Just a test, you can safely delete me !' | |
}; | |
var dataString = JSON.stringify(data); | |
var postEmailOptions = { | |
auth: companySlug + ':' + apiKey, | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'Content-Length': dataString.length | |
} | |
}; | |
function postMessage(route, done) { | |
// parse the target url, | |
var routeInfo = url.parse(route); | |
postEmailOptions.host = routeInfo.hostname; | |
postEmailOptions.port = routeInfo.port; | |
postEmailOptions.path = routeInfo.path; | |
var req = https.request(postEmailOptions, function (res) { | |
if (res.statusCode === 200) | |
return done(null); | |
else | |
return done('ERROR'); | |
}); | |
req.write(dataString); | |
req.end(); | |
} | |
getInboxList(function (err, inboxList) { | |
if (err) | |
return console.log(err); | |
// inboxList will be: | |
// [ | |
// alias: 'support', | |
// name: 'Support', | |
// type: 'imap', | |
// address: 'suport@mycompany.com', | |
// links: { | |
// messages: 'webhooks.frontapp.com/api/1/inboxes/support/messages', | |
// inbox: 'webhooks.frontapp.com/api/1/inboxes/support' | |
// } | |
// ] | |
postMessage(inboxList[0].links.messages, function (err) { | |
if (err) { | |
console.log(err); | |
process.exit(1); | |
} | |
console.log('OK'); | |
process.exit(0) | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment