Last active
October 26, 2016 12:03
-
-
Save wokamoto/b512a80281a878b3c946ce8552e1d8d6 to your computer and use it in GitHub Desktop.
[AWS][SES] SES で S3 に受信したメールを Slack に通知 ref: http://qiita.com/wokamoto/items/d740a19ad7ee0d48b2c3
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
/* | |
Name: Email Forwarder | |
*/ | |
exports.handler = function(event, context) { | |
var slackConfig = { | |
hostname: "hooks.slack.com", | |
path: "/services/XXXXXXXXX/XXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX", | |
channel: "#channel", | |
icon_emoji: ":ses:", | |
color: "good" | |
}; | |
var aws = require('aws-sdk'); | |
var async = require('async'); | |
var bucket = event.Records[0].s3.bucket.name; | |
var key = event.Records[0].s3.object.key; | |
async.waterfall([ | |
function(nextProcess) { | |
var s3 = new aws.S3({apiVersion: '2006-03-01'}); | |
s3.getObject({Bucket:bucket, Key:key}, nextProcess); | |
}, | |
function(data, nextProcess) { | |
var MailParser = require("mailparser").MailParser; | |
var mailparser = new MailParser(); | |
// setup an event listener when the parsing finishes | |
mailparser.on("end", function(result){ | |
console.log("Receive Mail: %j", result); | |
nextProcess(null, result); | |
}); | |
// send the email source to the parser | |
mailparser.write(data.Body.toString()); | |
mailparser.end(); | |
}, | |
function(mail_object, nextProcess) { | |
var https = require('https'); | |
var util = require('util'); | |
var options = { | |
method: 'POST', | |
hostname: slackConfig.hostname, | |
port: 443, | |
path: slackConfig.path | |
}; | |
var postData = { | |
"channel": slackConfig.channel, | |
"username": mail_object.from[0].name + "(" + mail_object.from[0].address + ")", | |
"text": "Subject: " + mail_object.subject + "\n" + | |
"From: " + mail_object.from[0].name + "(" + mail_object.from[0].address + ")" + "\n" + | |
"To: " + mail_object.to[0].address, | |
"icon_emoji": slackConfig.icon_emoji | |
}; | |
postData.attachments = [{ | |
"color": slackConfig.color, | |
"text": mail_object.text | |
}]; | |
var req = https.request(options, function(res) { | |
nextProcess(null, res); | |
}); | |
req.on('error', function(err) { | |
console.log('problem with request: ' + err.message); | |
nextProcess(err); | |
}); | |
req.write(util.format("%j", postData)); | |
req.end(); | |
}], | |
function(err, res) { | |
if (err) { | |
console.log('err: %j', err); | |
context.fail(err); | |
} else { | |
console.log('result: %j', res); | |
context.succeed('Success!'); | |
} | |
} | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment