Skip to content
PHP Logo

What are some best practices for sending mass emails in PHP while considering the max_execution_time limit?

When sending mass emails in PHP, it's important to consider the max_execution_time limit set in the PHP configuration. To avoid hitting this limit when sending a large number of emails, you can break up the email sending process into smaller batches and use a loop to send emails in chunks. This way, each batch of emails will be processed within the time limit, preventing the script from being terminated prematurely.

php
// Set the maximum execution time for the script
set_time_limit(0); // 0 means no time limit

// Define the batch size for sending emails
$batchSize = 50;

// Loop through the list of emails and send them in batches
$emails = array('email1@example.com', 'email2@example.com', 'email3@example.com', ...);

for ($i = 0; $i < count($emails); $i += $batchSize) {
    $batchEmails = array_slice($emails, $i, $batchSize);
    
    foreach ($batchEmails as $email) {
        // Code to send email to $email
    }
}