phplaravelemailmailgunbulk-email

Personalised batch email with Mailgun in Laravel


I'm looking to send personalised batch e-mails to a large number of users. By this I mean that I would like to set up a template e-mail and inject each user's information into it before sending it.

Of course, this can easily be achieved with Laravel by looping through user data and using the Mailer (Or Mail facade) methods (Such as send, raw, queue etc.):

foreach ($users as $user) {
    $data = ['user' => $user];
    $this->mailer->queue($views, $data, function($message) use($user) {
        $message->to($user->email, $user->name);
    });
}

However, considering the volume of e-mails I would like to send, this would be far too slow for my needs. After some research I have discovered that Mailgun supports sending personalised batch e-mails using their API. From their website:

Batch sending

With a single API call, you can send up to 1000 fully personalized emails.

Mailgun will properly assemble the MIME message and send the email to each of your users individually. That makes sending large volumes of email a lot faster and a lot less resource intensive.

Of course, I could happily implement this using Mailgun's API directly or using any available SDKs, but just wanted to check to see if it is supported by Laravel first.


Solution

  • Here's how I solved an identical situation since I couldn't find any ready made solution.

            $subscribers = Subscriber::active()->get();
            $batch = 0;
            $batch_subscribers = array();
            $batch_subscribers_data = array();
            foreach ($subscribers as $subscriber)
            {
                $batch_subscribers[] = $subscriber->mail;
                $batch_subscribers_data[$subscriber->mail] = array(
                    "id" => $subscriber->id,
                    "mail" => $subscriber->mail,
                    "name" => $subscriber->name
                );
                $batch++;
                if($batch < 999){
                    continue;
                }
                $input['to'] = $batch_subscribers;
                $input['vars'] = $batch_subscribers_data;
                Mailgun::send('email/email-base', ['input' => $input],
                    function ($message) use ($input) 
                    {
                        $message->subject($input['asunto']);
                        $message->to($input['to']);
                        $message->replyTo("reply@address.com");
                        $message->recipientVariables($input['vars']);
                    });
                $batch_subscribers = array();
                $batch_subscribers_data = array();
                $batch = 0;
            }