Send an Email Using Twilio SMS in PHP with SendGrid

May 28, 2020
Written by
Ladapo Samuel
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Send an Email Using Twilio SMS in PHP with SendGrid.png

One of the most amazing and forgotten features of SMS is that it works with no internet access. If you’re one of the 3.5 billion people in the world that uses a smartphone, you might not be aware of the millions that don’t use their finger to swipe their screens. India alone accounts for 400 million feature phones still in use in the world.

This might be hard to imagine, but assume you’re in a tight situation and you need to send a quick email and have no internet access. Maybe it’s a job posting you saw or an opportunity that can’t wait until you reach your laptop. It would be helpful if you could still send an email using SMS! In this tutorial, we’re going to learn how to do just that; send email using SMS.

Technical Requirements

Your computer will need to be set up to with the following tools and packages:

Set Up Your Development Environment

To start you will need to create a folder in your computer where you will be keeping all the necessary files required to start sending emails using SMS. For this tutorial, I’ll call the folder sms_email.

After creating this folder, the following empty files will need to be created inside of it:

  1. .env
  2. functions.php
  3. webhook.php

Run the following command below to complete all actions simultaneously:

$ mkdir sms_email && touch .env webhook.php functions.php

NOTE: The .env file is a hidden file used to store secret and private keys on your server. It is not accessible by the browser, so we can safely store API keys or credentials in it and access them from anywhere within our app on the server-side.

Install the Required Packages

To enable the support of the .env file,  you’ll need to install the PHP dotenv package using Composer. Run this command in your terminal inside of the project directory:

$ composer require vlucas/phpdotenv

The Twilio PHP SDK will now need to be installed in order to connect your project to Twilio’s APIs. Run the following command in your terminal:

$ composer require twilio/sdk

Setup Twilio Credentials & Phone Number

If you have not already done so, take a few minutes and head to your Twilio account to create a new number. You will need to get the following information from the Twilio console to send and receive SMS from your project:

  • Twilio Account SID
  • Twilio Auth Token
  • A Phone Number in E.164 format

Once you have located these items, add them to your .env file.

# TWILIO CREDENTIALS
TWILIO_ACCOUNT_SID=""
TWILIO_AUTH_TOKEN=""
TWILIO_PHONE_NUMBER="+1999999999"

Setup Twilio SendGrid Credentials for Sending Emails

SendGrid is a cloud-based SMTP provider owned by Twilio that allows you to send email without having to maintain email servers.

Only the SendGrid PHP package and a SendGrid API key are required to enable sending of emails within your application. First you need to generate a SendGrid API key.

Once you have your key, update your .env as follows:

# SENDGRID CREDENTIALS
SENDGRID_API_KEY=""

Now install SendGrid’s PHP package by running the following command in your terminal:

$ composer require sendgrid/sendgrid

Create an Email Sending Helper Function

You are now going to create a simple helper function that accepts a few parameters, processes them, and sends messages to the recipient using SendGrid.

Below is a simple email sending function using SendGrid. Add the following code to the functions.php file:

<?php
require __DIR__ . "/vendor/autoload.php";
$dotenv = Dotenv\Dotenv::create(__DIR__);

$dotenv->load();


/**
 * Sendgrid Send email function
 * @param $subject
 * @param $body
 * @param $to
 * @return int
 * @throws \SendGrid\Mail\TypeException
 */
function sendEmail($subject, $body, $to)
{
    $email = new \SendGrid\Mail\Mail();
    $email->setFrom(getenv('FROM_EMAIL'), getenv('FROM_NAME'));
    $email->setSubject($subject);
    $email->addTo($to);
    $email->addContent("text/plain", $body);
    $email->addContent(
        "text/html",
        $body
    );
    $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
    try {
        $response = $sendgrid->send($email);
        return $response->statusCode();
    } catch (Exception $e) {
        echo 'Caught exception: ' . $e->getMessage() . "\n";
    }
}

/**
 * Takes and processes the user's input, sends email.
 * @param $message
 * @return array|string[]
 * @throws \SendGrid\Mail\TypeException
 */
function processAndSendEmail($message)
{
    //TO:sam@mail.io+SUBJ:Hello+MSG: Im sending this email using SMS
    //we split the first input command
    $RawCommand = explode("+", $message);
    if (count($RawCommand) === 3) {
        //extract the useful data by splitting again using :
        $To = explode(":", $RawCommand[0])[1];
        $Subj = explode(":", $RawCommand[1])[1];
        $Msg = explode(":", $RawCommand[2])[1];
        //send email
        $sendEmail = sendEmail($Subj, $Msg, $To);
        //if email send success
        if ($sendEmail === 202) {
            $resp = ['status' => 'success', 'data' => [
                'to' => $To,
                'Subject' => $Subj,
                'Message' => $Msg
            ]];
        } else {
            //if email send fails
            $resp = ['status' => 'failed', 'message' => 'Message could\'nt be sent please try again'];
        }
    } else {
        //if user syntax is incorrect
        $resp = ['status' => 'failed', 'message' => 'Message could\'nt be sent please check your syntax'];
    }

    return $resp;
}

NOTE: The FROM_EMAIL and FROM_NAME variables will need to be added to your .env file using your respective values.

Create a Twilio Webhook

When text messages are sent to your Twilio designated number, Twilio sends a response containing information about your SMS back to your application using a Twilio webhook.

You will need to create your own webhook to receive and process the email sending requests. In the webhook.php file, copy and paste the following code into it.

<?php
require __DIR__ . "/vendor/autoload.php";
require_once('functions.php');

use Twilio\Rest\Client;

$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $message = $_REQUEST['Body'] ?? '';
    $from = $_REQUEST['From'] ?? '';
    if ($message !== '') {
        $account_sid = getenv("TWILIO_ACCOUNT_SID");
        $auth_token = getenv("TWILIO_AUTH_TOKEN");
        $twilio_number = getenv("TWILIO_PHONE_NUMBER");
        $client = new Client($account_sid, $auth_token);
        $response = processAndSendEmail($message);
        $text = '';
        if ($response['status'] === 'success') {
            $text = 'Message was sent to ' . $response['data']['to'] . ' Successfully';
        } else {
            $text = $response['message'];
        }

        $client->messages->create(
            $from,
            array(
                'from' => $twilio_number,
                'body' => $text
            )
        );
    }
}

If you’re made it this far, congratulations! You’re now only a few steps away from sending emails using SMS.

Setting up the Webhook URL

After setting up your webhook.php function, you will need to assign a URL to the phone number on your Twilio settings page. From there, each time you send an SMS to your Twilio designated number, Twilio will send data to this URL and then to your functions.php for processing.

For this tutorial, I am working from my local system and there’s no way to route my local URL to Twilio because my local dev environment is not connected to the internet. That’s where ngrok comes in. Ngrok allows your application to be accessed over the internet.

If you don’t have ngrok set up on your computer, you can see how to do so by following the instructions on their official download page.

In my own case, I’m going to run my PHP application using its built-in server.From the terminal, run the following command to start the server:

$ php -S localhost:3000

Now in a new terminal window, start ngrok by assigning it to the same port as the active PHP server:

$ ./ngrok http 3000

Your terminal window should look like this:

ngrok dashboard

Your Twilio project will use the Forwarding URL provided above, followed by the path to our webhook file. For example, mine is:

http://572b1fcb.ngrok.io/webhook.php

The final step is hooking your Twilio number to the webhook we created. Navigate to the active numbers on your dashboard and click on the number you would like to use. In the Messaging section, there is an input labeled “A MESSAGE COMES IN”. Replace the URL with your webhook URL and click “Save”!

Twilio phone numbers dashboard

Testing Our App

Send an SMS with the following format to your Twilio Number: TO:ladaposamuel@gmail.com+SUBJ:Hello+MSG:I’m sending this email using Twilio SMS

Successful screenshot
Successful email

Conclusion

Good job! Now we can send emails using SMS. You can extend the project to be a little bit more fun by making the SMS seem interactive like a chatbot and also including allowing sending to multiple addresses.

Bonus

Github Repo: https://github.com/ladaposamuel/twilio_sms_email

Ladapo Samuel