Skip to content

Instantly share code, notes, and snippets.

@ewandennis
Last active January 11, 2017 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ewandennis/ce01ebec96c9ac302a36a8313fda53fa to your computer and use it in GitHub Desktop.
Save ewandennis/ce01ebec96c9ac302a36a8313fda53fa to your computer and use it in GitHub Desktop.
SparkPost relay webhooks sample
'use strict';
/* Receive and extract email attachments using SparkPost relay webhooks.
*
* Prerequisites:
* - An inbound domain: https://developers.sparkpost.com/api/inbound-domains.html
* - A relay webhook: https://developers.sparkpost.com/api/relay-webhooks.html
*/
/*
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.14.0",
"mailparser": "^0.6.1"
}
*/
let express = require('express')
, bodyParser = require('body-parser')
, fs = require('fs')
, MailParser = require('mailparser').MailParser
, port = process.env.PORT || 3000
, app = express();
app.use(bodyParser.json({limit: '25mb'}));
app.post('/', (req, res) => {
req.body.forEach(msg => {
let content = msg.msys.relay_message.content
, body = content.email_rfc822
, parser = new MailParser({
streamAttachments: true
});
if (content.email_rfc822_is_base64) {
body = Buffer.from(body, 'base64');
}
parser.on('attachment', (attachment, mail) => {
console.log(`Writing ${attachment.fileName}...`);
attachment.stream.pipe(fs.createWriteStream(attachment.generatedFileName));
});
parser.on('end', mail => {
res.status(200).end();
});
parser.write(body);
parser.end();
});
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment