Send Transactional Emails in PHP with Twilio SendGrid

October 30, 2019
Written by

Transactional Emails in PHP with Twilio SendGrid

Your inbox is undoubtedly full of transactional emails. While they prevent you from getting to inbox zero, without them, you’d have a less informative Internet experience.

Transactional emails are those sent from within an application when a certain event is triggered. In the case of an e-commerce store, you would send a transactional email when the user has completed their account signup and when they successfully complete their purchase.

Historically, sending an email in PHP has been one of the simplest tasks to complete. With only the mail() function, you need only to insert a call to the mail() function within any part of your workflow to send a transactional email.

It’s simplicity, though, has also been its downfall. If you are unfamiliar with the mail() function, know that PHP developers have a love-hate relationship with it because, while it’s easy to implement, it has its challenges with bulk messaging and deliverability through SPAM filters. This is largely why transactional email products such as Twilio SendGrid exist, to ensure that emails arrive successfully, every time.

This tutorial will teach you how to use Twilio SendGrid to send transactional emails in PHP.

Tools Needed to Complete This Tutorial

Because you’re building this logic in one PHP file, there aren’t too many prerequisites for this tutorial. Make sure you have the following dependencies installed:

Create a New Project Folder and Files

In your console window, run the following commands to generate a project folder and source file:

$ mkdir php-sendgrid && cd php-sendgrid
$ touch email.php

Set Up the Composer Project

Composer is a tool for dependency management in PHP. It allows you to easily declare which libraries your project needs. In your console window, create a new composer.json file by running the following command:

$ touch composer.json

Open the newly created file in your IDE by running open composer.json and add the following declaration:

{
    "require": {}
}

Run composer install to generate the vendor directory.

Install Dotenv

Next, you’ll need a way to securely store your Twilio SendGrid API Key. The phpdotenv package by Vance Lucas will create a mechanism to load environment variables from a .env file to getenv(), $_ENV and $_SERVER. Let’s install it by running the following command:

$ composer require vlucas/phpdotenv && touch .env

Let’s create a placeholder for our API key by adding the following variable to our file:

SENDGRID_API_KEY=""

Sign Up for a Twilio SendGrid API Key

As mentioned before, we will use Twilio SendGrid to supply our transactional emails. After you create your SendGrid account, navigate to your dashboard in order to generate an API key.

Create Twilio SendGrid API key

Give the API Key a name such as “PHP Emails” and select “Full Access” for the API Key permissions.

Click on “Create & View” and copy the newly created key to the SENDGRID_API_KEY variable in your .env file.

NOTE: You will not be able to retrieve the API key after you leave this page. Be sure to copy and paste it somewhere safe for retrieval at a later time, if desired.

Install the Twilio SendGrid PHP SDK

Now that the Twilio SendGrid API key has been generated, you’ll need to install the SendGrid PHP SDK in order to access the SendGrid API. Run the following command:

$ composer require sendgrid/sendgrid

Create the Code to Send a Transactional Email

You’re ready to create the code to send your transactional email! Add the following code to the email.php file:

<?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("mbattle@twilio.com", "Marcus Battle");
$email->setSubject("Sending with SendGrid is Fun");

$email->addTo("marcus@marcusbattle.com", "Marcus Battle");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent("text/html", "and easy to do anywhere, even with PHP");

$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";
}

Testing

From the console window, run the following command: php email.php

Example SendGrid email

NOTE: Based on your domain settings, it is possible that your email was blocked by Google’s DMARC policy. If you notice that the email was successfully sent, but put on the blocked list, change the email “from” address to an acceptable domain.

Conclusion

It’s amazing that with less than thirty lines of code, you have transactional emails working in a stand-alone PHP script. This logic could be used to provide transactional emails in any existing PHP application.

We could even extend this further by providing transactional SMS at the same time an email is sent.

 

Marcus Battle is the PHP Developer of Technical Content at Twilio. He is committed to prompting and rallying PHP developers across the world to build the future of communications. He can be reached on Twitter at @themarcusbattle and via email.