How can PHP code be optimized and streamlined to avoid unnecessary complexity when using PHPMailer?

To optimize and streamline PHP code when using PHPMailer, avoid unnecessary complexity by using a clean and organized structure for sending emails. This can be achieved by creating reusable functions for sending different types of emails, avoiding redundant code, and properly handling errors and exceptions.

// Example of a streamlined PHP code using PHPMailer for sending emails

require 'vendor/autoload.php'; // Include PHPMailer autoload file

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function sendEmail($to, $subject, $body) {
    $mail = new PHPMailer(true); // Create a new PHPMailer instance

    try {
        // Server settings
        $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;

        // Recipients
        $mail->setFrom('from@example.com', 'Your Name');
        $mail->addAddress($to);

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $body;

        $mail->send();
        echo 'Email sent successfully';
    } catch (Exception $e) {
        echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
    }
}

// Example of sending an email using the sendEmail function
sendEmail('recipient@example.com', 'Test Email', 'This is a test email message.');