4
votes

It's very clear how you should forward an SMS to an email address using twilio - they have a good example of doing it with php code hosted on a third party server.

However, I would like to forward an SMS to an email address using ONLY a twiml app and no other third party request / code. I attempted this using the function:

<Response>
<Message to="[email protected]">{{From}}: {{Body}}</Message>
</Response>

... but this did not work, presumably because only accepts a phone number as the "to:".

Is it possible to do this using only a twiml bin ?

2

2 Answers

5
votes

OK you said no 3rd party request/code, but how about a request to Google and your own code?

If you have a Gmail account you can do it with Google Scripts. They host the code for you and it's pretty easy.

Go to https://script.google.com and create a new project, delete the code in the window and paste in the following, replacing the email address with the one you want to get the emails sent to.

function doGet(e){
 var from = e.parameter.From;
 var to = e.parameter.To;
 var body = e.parameter.Body;
 var emailAddress = '[email protected]';
 var message = body;
 var subject = 'SMS from ' + from + ' to ' + to + ' received';
 MailApp.sendEmail(emailAddress, subject, message);
 var output = ContentService.createTextOutput('<Response/>');
 output.setMimeType(ContentService.MimeType.XML);
 return output;
}

From the Publish menu choose deploy as web app. Set Execute the app as: to Me, then set Who has access to the app: to Anyone, even anonymous.

Now click deploy and Google will ask you to authenticate your script to allow it to send email as you (but not access your incoming email). Once you have granted permission it will give you the URL for your script.

Paste this URL into your Twilio console as the webhook handler for when a message comes in and set the method to HTTP GET

All this will do is email you the SMS. Change the <Response/> in the line below to contain TwiML for replying to the sender or whatever else you want Twilio to do when messages come in.

var output = ContentService.createTextOutput('<Response/>');

Obviously this is just a basic example, there's no authentication/security etc so any call to your script URL will send you an email. You should really secure it, although the URL Google generates isn't the kind anyone is likely to stumble upon.

1
votes

Twilio developer evangelist here.

You can't forward SMS messages to an email address with just a TwiML Bin. You are right, the <Message> TwiML does only accept a phone number in the to attribute.

This could be done using a Twilio Function and some Node.js code. I haven't done that before so would have to spend some time building it in order to tell you how.

There is an example here of how to build an app that forwards SMS to email using PHP.

Alternatively, you could set up Zapier to forward SMS messages to your email.

Let me know if that helps at all.