Create Transactional Emails you can Reply to in PHP with Twilio SendGrid Inbound Parse

November 13, 2019
Written by
Charles Oduk
Contributor
Opinions expressed by Twilio contributors are their own

Replyable Transactional Emails in PHP with Twilio SendGrid Inbound Parse.png

You’ve probably received many emails sent in the format noreply@somedomain.com. The irony of no-reply emails are that they often contain information that we would like to respond to. It would be great for businesses sending transactional emails to empower customers to respond to these emails.

Allowing replies to transactional emails is now possible with Twilio SendGrid. This tutorial will teach you how to use Twilio SendGrid Inbound Parse to place a second order to a mock e-commerce store, by replying to a transactional email.

Tutorial Requirements

This tutorial will require the following dependencies:

Create a Development Environment

From your console window, create a new project directory. Add three files to the newly created directory:

  • Webhook.php
  • Email.php
  • .env
$ mkdir SendGrid && cd SendGrid
$ touch Webhook.php Email.php .env

Install Dependencies

This project will require two dependencies:

  • PHP Dotenv, which makes it possible for us to load environment variables from the env file.
  • SendGrid PHP SDK, which enables us to work with the SendGrid API.

Add them to your project by running the following command:

$ composer require vlucas/phpdotenv sendgrid/sendgrid

Create a Twilio SendGrid API Key

Navigate to your SendGrid dashboard and create a new API key with full access. Copy the API Key and save it in the .env file we created earlier.

SENDGRID_API_KEY=”INSERT YOUR API KEY HERE”

Set Up the Code for Sending an Email

This project will need to send out an email so that you can test inbound responses. In Email.php copy the following code:

<?php
require 'vendor/autoload.php';

// Load our `.env` variables
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();

// Declare a new SendGrid Mail object
$email = new \SendGrid\Mail\Mail();

// Set the email parameters
$email->setFrom("sales@parse.charlesoduk.dev", "Charles Oduk");
$email->setSubject("Order #456557");
$email->addTo("odukjr@gmail.com", "Charles Oduk");
$email->addContent("text/plain", "Thank you for the purchase! If you need to
make another order of this item, respond to this email with the text ‘#Another one’.");

$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));

// Send the email
try {

  $response = $sendgrid->send($email);
   print $response->statusCode() . "\n";
   print_r($response->headers());
   print $response->body() . "\n";
   echo "email sent!\n";

} catch (Exception $e) {
   echo 'Caught exception: '. $e->getMessage() ."\n";
}

Note: The setFrom field contains a subdomain that I set up for the inbound parse. Instructions to set up your domain are in the next step.. Make sure you update it with your domain or subdomain.

Set Up the Inbound Parse Webhook

The inbound parse webhook processes emails from a domain or subdomain. The content of the email is parsed and posted to a URL of your choice. You will create a URL for your email content to be sent to. Using ngrok, make Webhook.php accessible through a public URL.

From the console window run the command:

$ php -S localhost:3000

In a new console run the command:

$ ngrok http 3000

You should see a URL similar to this:

https://258f1acb.ngrok.io

To set up your domain follow the instructions in this article. The destination URL will use the ngrok URL you just created, followed by /webhook.php. This is what mine looks like:

https://258f1acb.ngrok.io/webhook.php

Here’s a screenshot of my inbound parse webhook:

 

Edit Host & URL

 

Add Inbound Parse Logic to Webhook.php

Now that the inbound parse webhook set up, add the code that handles the content that will be sent to it in the Webhook.php.

<?php

require 'vendor/autoload.php';

// Load our `.env` variable
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();

// Declare a new SendGrid Mail object
$email = new \SendGrid\Mail\Mail();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $from = $_POST["from"];
  $body = $_POST["text"];
  $subject = $_POST["subject"];

  $body = explode("\n", $body);

  preg_match('#\<(.*?)\>#', $from, $match);
  $fromEmail = $match[1];

  $name = explode("<", $from);

  $order = explode(":", $subject);

  if ($body[0] === "#Another one") {
    // Set the email parameters
    $email->setFrom("reorder@charlesoduk.dev", "Charles Oduk");
    $email->setSubject("Another one!");
    $email->addTo($fromEmail, $name[0]);
    $email->addContent("text/plain", "Thanks $name[0], we have
    made another dispatch for your previous order:$order[1]");
    $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
    $sendgrid->send($email);
  }
}

Testing

From a new console window send the first email. Run the command:

$ php Email.php

You should get an email like this:

 

Sample email order notification

Reply to the email with the text #Another one. You should now receive another email similar to this:

Another sample email order notification

Additional Resources

Checkout the Transactional Email SendGrid Documentation to learn more about what can be accomplished with transactional emails in Twilio SendGrid.

Twilio’s Marcus Battle has also written a tutorial that will teach you how to how to Send Transactional Emails in PHP with Twilio SendGrid.

Conclusion

Great work! You have just made use of the inbound parse webhook. We have just scratched the surface with a simple example. You could go ahead and implement the ordering system using Order Desk.

 

I look forward to seeing what you build. You can reach me on:

Email: odukjr@gmail.com

Twitter: @charlieoduk

Github: charlieoduk