What are the best practices for sending a large number of emails in PHP, especially when dealing with a mailing list from a database?

Sending a large number of emails in PHP can be resource-intensive and slow, especially when dealing with a mailing list from a database. To optimize this process, it's best to use a batch processing approach where emails are sent in chunks rather than all at once. This helps prevent timeouts and reduces server load.

// Connect to the database and retrieve email addresses in batches
$batchSize = 100; // Number of emails to send in each batch
$offset = 0;

do {
    $query = "SELECT email FROM mailing_list LIMIT $offset, $batchSize";
    $result = mysqli_query($conn, $query);

    while ($row = mysqli_fetch_assoc($result)) {
        $email = $row['email'];
        // Send email logic here
    }

    $offset += $batchSize;

    // Delay to prevent server overload
    usleep(500000); // 0.5 seconds delay

} while (mysqli_num_rows($result) > 0);