Forwarding SMS Messages to Email Using PHP

    Overview

    Businesses get communications through many channels. It can be handy to have a searchable archive of messages in one place. Forwarding SMS messages to email lets you keep both kinds of messages in one spot. Plivo makes it easy to forward SMS messages to email using the most popular web development languages. Here we walk through the process with .NET.

    Prerequisites

    • Plivo account: Sign up for a Plivo account if you don’t have one already.

    • Plivo phone number: To receive SMS, you must have a Plivo phone number that supports SMS. You can purchase numbers from the Numbers page of the Plivo console or by using the Numbers API.

      Buy a New Plivo Number

    The code example below presumes you have a Gmail account, but it’s easy to edit the code to support another SMTP client.

    Install PHP and other modules

    You must set up and install PHP and to forward Incoming SMS to an Email.

    Install PHP

    Operating SystemInstructions
    macOSYou can install PHP using the official installer. You can also install it from here.
    LinuxTo install PHP on Linux you can find the instructions here.
    WindowsTo install PHP on Windows you can use the official installer.

    Install Composer

    Composer is a dependency manager for PHP that is used in all modern PHP frameworks, such as Symfony and Laravel. We highly recommend using Composer as the package manager for your web project.

    1. Download the latest version of Composer.
    2. Run the following command in Terminal in order to run the composer:

       $ php ~/Downloads/composer.phar --version
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make it executable:

       $ cp ~/Downloads/composer.phar /usr/local/bin/composer
       $ sudo chmod +x /usr/local/bin/composer
       $ Make sure you move the file to bin directory.
      
    4. To check if the path has /usr/local/bin, use

       $ echo $PATH
      

      If the path is different, use the following command to update the $PATH:

       $ export PATH = $PATH:/usr/local/bin
       $ source ~/.bash_profile
      

      Note: If your PATH doesn’t include /usr/local/bin directory, we recommend adding it so that you can access it globally.

    5. You can also check the version of Composer by running the following command:

       $ composer --version.       
      

    1. Run the following command:

       $ curl -sS https://getcomposer.org/installer | php
      
    2. Run the following command to make the composer.phar file as executable:

       $ chmod +x composer.phar
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make Composer globally available for all system users:

       $ mv composer.phar /usr/local/bin/composer
      

    1. Download and run the Windows Installer for Composer.

      Note: Make sure to allow Windows Installer for Composer to make changes to your php.ini file.

    2. If you have any terminal windows open, close all instances and open a fresh terminal instance.
    3. Run the Composer command.

       $ composer -V
      

    Install Laravel & Create a Laravel Project

    • Use the below command to install Laravel:

      $ composer require laravel/installer
      

    As we have Laravel and its dependencies installed, we can use them to create a new Laravel project. As the initial step, using Laravel we can auto-generate code in the Laravel folder structure.

    • create the directory to our project & change directory in the command line:

      $ mkdir mylaravelapp
      $ cd mylaravelapp
      
    • Use the below command to start your Laravel project:

      $ composer create-project laravel/laravel quickstart --prefer-dist
      
    • To install the dependency modules, run the following command in the project directory:

      $ cd quickstart 
      $ composer require phpmailer/phpmailer
      

    Create a Laravel Controller

    Change the directory to our newly created project directory, i.e, quickstart directory and run the below command to create a Laravel controller.

    $ php artisan make:controller EmailController
    

    This will generate a controller named EmailController in the app/http/controllers/ directory. Now, You have to open the app/http/controllers/emailController.php file and add the following code:

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    
    <?php
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    
    class EmailController extends Controller
    {
        public function forwardemial()
        {
            $mail = new PHPMailer(true);
    
            try
            {
                $from_number = $_REQUEST["From"];
                // Receiver's phone number - Plivo number
                $to_number = $_REQUEST["To"];
                // The text which was received on your Plivo number
                $text = $_REQUEST["Text"];
    
                echo ("Message received from $from_number:$text:$to_number");
    
                //Server settings
                $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
                $mail->isSMTP(); //Send using SMTP
                $mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through
                $mail->SMTPAuth = true; //Enable SMTP authentication
                $mail->Username = '<email_address>'; //SMTP username
                $mail->Password = '<password>'; //SMTP password
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
                $mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
                //Recipients
                $mail->setFrom('<from_email_addres>', 'Mailer');
                $mail->addAddress('<recepient_email_address>', 'Joe User'); //Add a recipient
                $mail->addAddress('<recepient_email_address>'); //Name is optional
                //Content
                $mail->isHTML(true); //Set email format to HTML
                $mail->Subject = 'Here is the subject' . $from_number;
                $mail->Body = 'This is the HTML message body <b>in bold!</b>';
                $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    
                $mail->send();
                echo 'Message has been sent';
            }
            catch(Exception $e)
            {
                echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
            }
        }
    
    }
    
    Note: If you use Gmail to send email, you'll have to use an app password, which will be treated as your password to send email from the app.

    Add a Route

    Now, to add a route for the forwardemail function in the EmailController class, open the routes/web.php file and add the below line at the end of the file:

    Route::match(['get', 'post'], '/forwardemail', 'EmailController@forwardemail');
    
    Note:
  • If you are using Laravel 8 then you need to use the fully qualified Class name for your Controllers. For example:
    Route::match(['get', 'post'], '/forwardemail', 'App\Http\Controllers\EmailController@forwardemail');
  • We have added the route of the app to the “except” array to disable CSRF verification - app/Http/Middleware/VerifyCsrfToken.php
  • Test & Validate

    Now the EmailController is ready forward incoming SMS to your email, you can use the below command to initiate.

    $ php artisan serve
    

    Your local development server will be started and you can test the laravel app via the URL http://127.0.0.1:8000/forwardemail/.

    Expose your local server to the internet

    To receive Incoming Messages and to handle callbacks, your local server should be able to connect with Plivo API service, Ngrok is a tunneling software used to expose a web server running on your local machine to the internet. Using Ngrok you can set webhooks which can talk to Plivo server.

    ngrok block diagram

    Install ngrok and run it on the command line, specifying the port that hosts the application on which you want to receive messages (8000 in this case):

    $ ./ngrok http 8000
    

    Ngrok will display a forwarding link that you can use as a webhook to access your local server over the public network.

    Sample ngrok CLI

    Create an Application

    1. Create a Plivo application by visiting Messaging > Applications and clicking on Add New Application, or by using Plivo’s Application API.
    2. Give your application a name — we called our Email SMS. Enter your server URL (for example https://84b781ed8406.ngrok.io/email_sms/) in the Message URL field and set the method as POST.
    3. Click on 'Create Application' to save your application.

    Create Application

    Assign a Plivo number to your app

    1. Navigate to the Numbers page and select the phone number you want to use for the application.
    2. Select XML Application from the Application Type drop-down list, and Email SMS (the name of the application) from the Plivo Application drop-down list.
    3. Click on 'Update Number' to save.

    Assign Application

    Test and validate

    Then send a text message to the Plivo number you associated with the application using a regular mobile phone.The incoming message should be reflected in your email.