What are some potential pitfalls when using PHP to send multiple emails within a loop?

One potential pitfall when using PHP to send multiple emails within a loop is that it can lead to performance issues and potential email delivery problems if not handled properly. To solve this, you can use a library like PHPMailer which allows you to send emails efficiently and reliably in a loop by creating a new instance of PHPMailer for each email and clearing the previous instance after sending.

// Include PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Loop through email addresses
foreach ($emailAddresses as $email) {
    // Create a new instance of PHPMailer
    $mail = new PHPMailer(true);
    
    try {
        // Set up the PHPMailer instance
        $mail->isSMTP();
        $mail->Host = 'smtp.example.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'your@example.com';
        $mail->Password = 'your_password';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        
        // Set email parameters
        $mail->setFrom('your@example.com', 'Your Name');
        $mail->addAddress($email);
        $mail->Subject = 'Subject';
        $mail->Body = 'Email body';
        
        // Send the email
        $mail->send();
        
        // Clear the PHPMailer instance
        $mail = null;
    } catch (Exception $e) {
        echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
    }
}