Last active
May 3, 2018 19:59
-
-
Save ilg/955eab354c627390f741fc312f19b31b to your computer and use it in GitHub Desktop.
Twilio function to forward SMS/MMS as email using AWS SES
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
const AWS = require('aws-sdk'); | |
AWS.config.update({region: 'us-west-2'}); | |
const mailcomposer = require('mailcomposer'); | |
const extName = require('ext-name'); | |
const urlUtil = require('url'); | |
const path = require('path'); | |
exports.handler = function(context, event, callback) { | |
let attachments = []; | |
for (var i = 0; i < event.NumMedia; i++) { | |
const mediaUrl = event[`MediaUrl${i}`]; | |
const contentType = event[`MediaContentType${i}`]; | |
const extension = extName.mime(contentType)[0].ext; | |
const mediaSid = path.basename(urlUtil.parse(mediaUrl).pathname); | |
const filename = `${mediaSid}.${extension}`; | |
attachments.push({path: mediaUrl, filename, contentType}); | |
} | |
const mail = mailcomposer({ | |
from: context.FROM_EMAIL_ADDRESS, | |
replyTo: context.FROM_EMAIL_ADDRESS, | |
to: context.TO_EMAIL_ADDRESS, | |
subject: `Message from ${event.From} (via Twilio to ${event.To})`, | |
text: event.Body, | |
attachments: attachments, | |
}); | |
mail.build((err, message) => { | |
if (err) { | |
return callback(err); | |
} | |
const ses = new AWS.SES({apiVersion: '2010-12-01'}); | |
ses.sendRawEmail({RawMessage: {Data: message}}, (err, data) => { | |
if (err) { | |
return callback(err); | |
} | |
callback(null, ''); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment