How to Send Bulk Emails in PHP using Twilio SendGrid

October 31, 2019
Written by

How to send bulk emails in PHP using Twilio SendGrid

Frequent and relevant communication with attendees is necessary when planning an event. There are too many opportunities for confusion if timely and detailed messages are not sent. Even when everything goes according to plan guests still need reminders as the event date draws closer.

Bulk emails are a great method to keep everyone in the loop.

In this tutorial, we will learn how to send bulk emails to an email list in PHP using Twilio SendGrid.

We’ll use a foreach() loop to parse through an array of email addresses and build a single array of recipients using SendGrid’s personalization class. SendGrid allows us to personalize each email that every recipient receives. We can even modify content based on the individual email address.

Tools Needed to Complete This Tutorial

To complete this tutorial you’ll need the following dependencies installed:

Get Started with Twilio SendGrid

Take a look at the Send Transactional Emails in PHP with Twilio SendGrid tutorial to get started. You’ll pick up from where that tutorial ends. You can also begin this tutorial by cloning the relative repository as follows:

$ git clone git@github.com:themarcusbattle/php-sendgrid.git
$ cd php-sendgrid

Create the Code to Send a Bulk Email

Now that you’ve completed the first part of this tutorial, you’re ready to create the code to send bulk emails. Open up email.php in the root directory and replace the contents with the following code:

<?php

require 'vendor/autoload.php';

use SendGrid\Mail\Personalization;
use SendGrid\Mail\To;

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

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

// Define the primary email
$email->setFrom("your@email.com", "Your Name");
$email->setSubject("Group Email to Twilio Subscribers");
$email->addTo("first@recipient.com", "First Recipient");

// Define the additional email addresses
$email_addresses = [
    'second@recipient.com',
];

foreach ( $email_addresses as $email_address ) {

    $personalization = new Personalization();
    $personalization->addTo( new To( $email_address ) );

    $email->addPersonalization( $personalization );
}


$email->addContent("text/plain", "Sending bulk emails is easy with SendGrid");
$email->addContent("text/html", "Sending bulk emails is easy with SendGrid");

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

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

The Personalization class works by appending an array of personalizations to an existing Mail object. You’ll notice the first recipient is assigned to the newly created $email object. Each additional recipient is defined in the $email_addresses array.

The SendGrid Mail object only accepts one primary recipient, so we will add each additional recipient by using the Personalization class. The $email_addresses are iterated over using a foreach loop. Each pass instantiates a new Personalization object and assigns the recipient using the addTo method. Once each Personalization is added to the parent Mail object $email they are all sent using the same logic as the first tutorial.

Testing

Run the following command in your console window from the root directory: php email.php

A successful execution will display emails sent! in your console window, preceded by the status code and headers from our email.

SendGrid email response in console window

Bulk email response

Conclusion

SendGrid really makes sending bulk emails easy, coincidentally increasing confidence that all your recipients stay up to date with mass notifications.

Take a look at the personalization class to see how you can fine-tune each email sent to your recipients.

 

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.