RLC_TPJM
RLC_TPJM

Reputation: 25

How to improve the efficiency of PHP mail sending?

I'm using PHP to send mails to multiple people in CakePHP.

I'm currently using foreach on the recipient array, which contains mail address and names, and send the mails. It's taking quite a while to send mails and can't be done as put recipients' mail as array since there's a tiny different between all mails such as receiver's names.

The mails are using same template but different parameters, is there anyway I can improve the efficiency of it?

Update: Here is the Email Template

<?= $userSex ?> <?= $userName ?>, <br>
Thanks for ordering!<br>
Your order's ID is "<?= $orderID ?>".<br>
You can check the shipping status on our website.<br>
Thank you and hope you have a wonderful day.

and here's the code.

$mail_list = {
    [0]=>{
        'userSex'=>'Miss',
        'userName'=>'V',
        'orderID'=>'xxxxxxxx'
    },
    [1]=>{
        'userSex'=>'Mr.',
        'userName'=>'Arasaka',
        'orderID'=>'xxxxxxxx'
    }
}
foreach($mail_list as $target) {
    $email = new Email();
    $email->viewBuilder()->setTemplate('notify_template');
    $email->setEmailFormat('html')
            ->setSubject($subject)
            ->setViewVars([
                'userSex' => $target['userSex'],
                'userName' => $target['userName'],
                'orderID' => $target['orderID'],
    ]);
    $emailRes = $email
        ->setFrom(['[email protected]' => 'service announence'])
        ->setTo($target['email'])
        ->setSubject($subject)
        ->send();
    if (!$emailRes) {
        $res = false;
        break;
    }
}

Every mail sent is slightly different.

Is there a way to improve the mailing speed?

Upvotes: 1

Views: 179

Answers (1)

istepaniuk
istepaniuk

Reputation: 4271

The speed of your mailing will be dictated by the speed of your configured transport (See https://book.cakephp.org/3/en/core-libraries/email.html#using-transports).

Sending the emails sequentially like this will always take time and it's normally done in some sort of background process (like a cron job).

If you really need to send emails quicker than what a quick transport can offer (for orders and other transactional email, I doubt it) you could investigate other options. Most email API services provide some sort of way to send bulk messages using templates (such as Sendgrid, Mandrill, Mailgun, Postmark, etc.)

Upvotes: 1

Related Questions