Search code examples
phptwiliosmsforwarding

How to Code PHP for Twilio to forward SMS to Email


Coding newby here.

I am trying to write some PHP code to enable SMS forwarding to email with a Twilio phone number. Unfortunately, I haven't had any success in doing so.

I saw some tutorials using SendGrid, but I would rather use my own PHP code on my web server.

Can anyone point me to a good source or if possible, provide step by step instructions?

Thank you


Solution

  • Twilio developer evangelist here.

    There is a "forward SMS to email" quick deploy here where you don't need a server--Twilio will host it for you!

    This is how you could do it with PHP:

    <?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 = "[email protected]";
    $subject = "Message from {$_REQUEST['From']} at {$_REQUEST['To']}"; 
    $message = "You have received a message from {$_REQUEST['From']}. Body: {$_REQUEST['Body']}"; 
    $headers = "From: [email protected]"; // Who should it come from?
    
    mail($to, $subject, $message, $headers); 
    

    To make that code above work,

    1. Modify the code below to update the From and To email addresses.
    2. Publish that file to a Twilio-accessible URL on your web server.
    3. Update your Twilio Phone Number's webhook with your application's URL.

    If you're a Node.js person, here is a tutorial that uses Twilio Functions, Twilio's serverless environment for hosting web (Node) apps.

    Let me know if this helps at all!