Incoming Twilio Programmable SMS Messages can be forwarded to an email inbox with just a few lines of code. Here are two examples to get you up and running quickly.
Forward Incoming SMS Messages using Twilio Functions
If you don't already have hosting for your code, Twilio Functions can be used to host your Node.js scripts. Our Dev team has put together a helpful guide showing how to use SendGrid in conjunction with Functions to forward messages to your email, complete with sample code. You can find the tutorial here: Forward incoming SMS messages to email with Node.js, SendGrid and Twilio Functions.
Forward Incoming SMS Messages using Webhooks
To host your own code as a Twilio webhook, you can use any language you like. The following example uses PHP. Here's what it takes to make this code work:
- Modify the code below to update the
From
andTo
email addresses. - Publish this file to a Twilio-accessible URL on your web server.
- Update your Twilio Phone Number's webhook with your application's URL.
<?php
/**
* This section ensures that Twilio gets a response.
*/
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<Response></Response>'; //Place the desired response (if any) here
/**
* This section actually sends the email.
*/
/* Your email address */
$to = "your-email@example.com";
$subject = "Message from {$_REQUEST['From']} at {$_REQUEST['To']}";
$message = "You have received a message from {$_REQUEST['From']}. Body: {$_REQUEST['Body']}";
$headers = "From: webmaster@example.com"; // Who should it come from?
mail($to, $subject, $message, $headers);
Any of the parameters which are part of the Twilio Request can also be used.