Skip to content

Instantly share code, notes, and snippets.

@charsi
Created January 10, 2018 12:07
Show Gist options
  • Save charsi/d2f377f559519bbbe287f12ef63daf0e to your computer and use it in GitHub Desktop.
Save charsi/d2f377f559519bbbe287f12ef63daf0e to your computer and use it in GitHub Desktop.
Twilio function for forwarding text messages to email using mailgun.
let toEmail = 'TO EMAIL ADDRESS';
let fromEmail = 'FROM EMAIl ADDRESS';
let mgKey = 'INSERT MAILGUN API KEY';
exports.handler = function(context, event, callback) {
//var mailgun = require('mailgun-js')({apiKey: context.MG_KEY, domain: context.MG_DOMAIN});
var domain = fromEmail.split('@')[1];
var mailgun = require('mailgun-js')({apiKey: mgKey, domain: domain});
var number = event.From;
var intCode = number.slice(0,-10);
if(intCode) {
intCode += ' ';
}
number =
intCode +
'(' +
number.slice(-10,-7) +
') ' +
number.slice(-7,-4) +
'-' +
number.slice(-4);
var data = {
from: event.From + '<' + fromEmail + '>',
to: toEmail, // This can be a list
subject: 'New SMS from '+ number,
text: event.Body,
//html: ' <b>html</b> is pretty :) \n' + event.From + ' sent:\n' + 'event.Body' ,
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
};
@politician
Copy link

politician commented Jan 13, 2020

Thanks for the code.
I have made a couple updates:

  1. Twilio has updated their requirements and a function needs to send a callback, so I am sending Mailgun's response as a callback
  2. Mailgun requires an extra parameter host for their EU clients

PS: don't forget to add the NPM dependency for mailgun-js in the Configure menu in Twilio

let toEmail = 'TO EMAIL ADDRESS';
let fromEmail = 'FROM EMAIl ADDRESS';
let mgKey = 'INSERT MAILGUN API KEY';
let mgHost = 'api.mailgun.net'; // Use 'api.eu.mailgun.net' if using Mailgun EU

exports.handler = function(context, event, callback) {
  //var mailgun = require('mailgun-js')({apiKey: context.MG_KEY, domain: context.MG_DOMAIN});
  var domain = fromEmail.split('@')[1];
  var mailgun = require('mailgun-js')({apiKey: mgKey, domain: domain});
  var number = event.From;
  
  var intCode = number.slice(0,-10);

  if(intCode) {
    intCode += ' ';
  }
  number =
    intCode +
    '(' +
    number.slice(-10,-7) +
    ') ' +
    number.slice(-7,-4) +
    '-' +
    number.slice(-4);

  var data = {
    from: event.From + '<' + fromEmail + '>',
    to: toEmail,  // This can be a list
    subject: 'New SMS from '+ number,
    text: event.Body,
    //html: '  <b>html</b> is pretty  :) \n'  + event.From + ' sent:\n' + 'event.Body' ,
  };

  mailgun.messages().send(data, function (error, body) {
    console.log(body);

    let twiml = new Twilio.twiml.MessagingResponse();
    callback(error, body.message);
  }); 
};

@RLHawk1
Copy link

RLHawk1 commented Apr 8, 2020

Thank you for sharing this! Very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment