Is using sendmail() to send multiple emails in a loop efficient in terms of performance?

Using sendmail() to send multiple emails in a loop can be inefficient in terms of performance because each call to sendmail() initiates a separate process to send the email. This can lead to a high overhead, especially when sending a large number of emails in quick succession. To improve performance, it is recommended to use a library or service that can handle bulk email sending efficiently.

// Example of using PHPMailer library to send multiple emails efficiently
require 'vendor/autoload.php'; // Include PHPMailer library

$mail = new PHPMailer\PHPMailer\PHPMailer();

// Loop through email addresses and send emails
$emails = ['email1@example.com', 'email2@example.com', 'email3@example.com'];
foreach ($emails as $email) {
    $mail->addAddress($email);
    $mail->Subject = 'Subject of the email';
    $mail->Body = 'Body of the email';
    
    if (!$mail->send()) {
        echo 'Error sending email to ' . $email . ': ' . $mail->ErrorInfo;
    } else {
        echo 'Email sent to ' . $email;
    }
    
    $mail->clearAddresses(); // Clear recipients for next email
}