PHP: Send Personalized Emails to Multiple Users

Have you ever wanted to send bulk emails that have dynamic content to multiple users? Well, you are not alone and I'll be showing you the exact code snippet I used for this purpose but in PHP. In order to successfully send emails, I made use of SendGrid PHP SDK which is a library by the Sendgrid team for sending emails efficiently and for FREE too.

Install Package

Add Twilio SendGrid to your composer.json file. If you are not using Composer, I highly recommend it. It's an excellent way to manage dependencies in your PHP application.

{
  "require": {
    "sendgrid/sendgrid": "~7"
  }
}

or simply just install via the terminal using the command:

composer require "sendgrid/sendgrid"

Get API key

An API key is required to authenticate your request and you can always get one when you signup on SendGrid. Once you have this key, copy and paste it somewhere in your project, for me, I've been able to read environment variables from a .env file using this package. Just find a way to store your API key and the security of that key is your concern, try not to push that key to public version control platforms like GitHub, Sendgrid would disable this API Key once they find out ( don't ask me how ), and this is bad for production.

Code

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

use SendGrid\Mail\From;
use SendGrid\Mail\Mail;
use SendGrid\Mail\Personalization;
use SendGrid\Mail\Subject;
use SendGrid\Mail\To;
use SendGrid\Mail\HtmlContent;
use SendGrid\Mail\Substitution;


function sendBulkMail($receipientsData, $from, $subject, $message, $fromName)
    {


        $from_ = new From($from, $fromName);
        $htmlContent = new HtmlContent(
            $message
        );
        $email = new Mail($from_,null,$subject,null, $htmlContent);

        foreach ($receipientsData as $reciepient) {

            $personalization = new Personalization();
            $personalization->addTo(new To(
                $reciepient[0],
                $reciepient[1]
            ));

            $personalization->setSubject(new Subject($subject));
             $personalization->addDynamicTemplateData(new Substitution("-first_name-",$reciepient[1]));            

        }

        $sendgrid = new \SendGrid($_ENV['SEND_GRID']);
        try {
           $response =  $sendgrid->send($email);
            print $response->statusCode() . "\n";

            return true;
        } catch (Exception $e) {
            return false;
        }
    }

$message = "<div>Hello -first_name-</div>";
sendBulkMail([["test@gmail.com","Alfred"],["test2@gmail.com","Star"]],"alfred@codemon.me","Test",$message,"Alfred");

The sendBulkMail function accepts the following parameter

  • A Multidimensional array of your users' data, each user has an email and a name, think of this as an array of arrays.

  • Senders email

  • Email Subject

  • HTML content ( you can use twig to load your HTML template )

  • Senders Name

Code Explanation

 $personalization = new Personalization();
 $personalization->addDynamicTemplateData(new Substitution("-first_name-",$reciepient[1]));

In order to personalize emails for each user, we construct a new Personalization class which has helpful methods to set dynamic data for each user. Calling the addDynamicTemplateData method on this class lets us substitute a placeholder with the actual valid on the HTML template. In our case, we want to replace -first_name- with the name of the current user.

It's important to note that your placeholder string (-first_name-) can take any format as you wish, it can look like this {{first_name}} as well.

 $sendgrid = new \SendGrid($_ENV['SEND_GRID']);

This line of code simply sets our API key and like mentioned earlier, I'm currently loading environment variables from a .env file, but you can as well just hardcode your API Key( not recommended).

Conclusion

Thanks to Sendgrid, you do not need to set up a ridiculous code block to send emails to multiple users, using this method is fast and saves some costs too. In this blog post, you've learned how to send personalized emails to multiple users using SendGrid PHP SDK, hope it made sense. Leave a comment with your questions and kind words, see you!