Mailgun API: Batch Sending vs. Individual Calls

Viewed 6596

Background

We're building an application that will process & send emails via Mailgun. These are sometimes one-off messages, initiated by a transaction. Some emails, though, will be sent to 30k+ at once.

Eg, a newsletter to all members.

Considerations

Mailgun offers a Batch Sending option with their API. Using "Recipient Variables", you can include dynamic values that are paired with a particular user.

This Batch Sending functionality is limited, however. You cannot send more than 1,000 recipients per request, which means we have to iterate through a recipient list (on our database) for each set of 1,000. Mailgun provides an example of how this might work, using Python (scroll about 2/3 down).

Question

Are there any advantages to batch sending (ie, sending an email to a group of recipients through a single API call, using recipient variables) as opposed to making our own loop, variable substitutions and individual API calls?

I assume this is more taxing on our server, as it would be processing each message itself, instead of just offloading all that data to Mailgun's server for heavy-lifting on their end. But I also like the flexibility & simplicity of handling that on our end and sending a "fully-rendered" message to Mailgun, one at a time, without having to iterate 1k at a time.

Any thoughts on best practices, or considerations we should take into account?

2 Answers

The answer of @cdwyer and @nikoshr is very helpful, but bit legacy. Used methods in the example are deprecated. Here is current usage of lib:


    $batchMessage = $this->mailgun->messages()->getBatchMessage('mydomain.com');


    $batchMessage->setFromAddress('user@domain.com');
    $batchMessage->setReplyToAddress('user2@domain.com');
    $batchMessage->setSubject('Contact form | Company');
    $batchMessage->setHtmlBody('<html>...</html>');

    foreach ($recipients as $recipient) {
        $batchMessage->addToRecipient($recipient);
    }

    $batchMessage->finalize();

More info at documentation.

Related