Sendgrid | How to send bulk emails in one batch using sendgrid in php

Author - Manju Kashyap

Recently we were working on a project in which the requirement was to send emails to 500 users at a time. Earlier, emails were being sent to 500 users in a loop 1 by 1 in which sendgrid-API was being called 500 times and this was consuming very huge amount of time and we were getting server timeout problem.

To solve this problem, we changed the code to send emails in a batch

bulk emails in one batch, sendgrid’s libraries can be used. You can download library as per your project’s technology using the following link:

Click here

I have downloaded sendgrid-php library and used in our php-project

Add following line at the top of your file:

include_once("path/to/sendgrid-php/sendgrid-php.php");

To begin using this library, initialize the SendGrid object with your SendGrid credentials OR a SendGrid API Key.

$sendgrid = new SendGrid('username', 'password');
// OR
$sendgrid = new SendGrid('sendgrid api key');

Create a new SendGrid Email object and add your message details with different recipients and their corresponding email subjects and messages in arrays.

$fromEmail = 'admin@mailinator.com';
$recipients = array('user1@mailinator.com','user2@mailinator.com', 'user3@mailinator.com');
$names = array('user1,'user2,'user2);
$subjects = array('test subject for user1’, 'test subject for user2’, 'test subject for user3 ’);
$messages = array('Testing message for user1 ',  'Testing message for user2 ',
        'Testing message for user3 ');

Create a single email object and set these arrays:

$email = new SendGridEmail();
$email
->setFrom($fromEmail)
->setSmtpapiTos($recipients)
->setSubject('%subject%')
->setSubstitutions(array
(
'%name%' => $names,
'%subject%' => $subjects,
'%body%' => $messages
)
->setHtml('%body%');

Then send you emails using following sendgrid method :

$sendgrid->send($email);

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *