How can one optimize the code for sending emails with attachments in PHP to improve performance and reliability?

To optimize the code for sending emails with attachments in PHP, you can use a library like PHPMailer which provides a more reliable and efficient way to send emails with attachments. PHPMailer handles the complexities of email sending, including attachments, and ensures better performance and reliability compared to using the built-in mail() function in PHP.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer();

// Set up the SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set the sender and recipient
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');

// Add attachments
$mail->addAttachment('/path/to/file1.pdf');
$mail->addAttachment('/path/to/file2.jpg');

// Set the email subject and body
$mail->Subject = 'Email with Attachments';
$mail->Body = 'This email contains attachments.';

// Send the email
if ($mail->send()) {
    echo 'Email sent successfully';
} else {
    echo 'Email sending failed';
}