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:
I have downloaded sendgrid-php library and used in our php-project
Add following line at the top of your file:
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 = 'firstname.lastname@example.org'; $recipients = array('email@example.com','firstname.lastname@example.org', 'email@example.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 :
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 firstname.lastname@example.org