Skip to content

Instantly share code, notes, and snippets.

@ilg
Last active May 3, 2018 19:59
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 ilg/955eab354c627390f741fc312f19b31b to your computer and use it in GitHub Desktop.
Save ilg/955eab354c627390f741fc312f19b31b to your computer and use it in GitHub Desktop.
Twilio function to forward SMS/MMS as email using AWS SES
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