How can PHPMailer be utilized to improve the security and functionality of email attachment handling in PHP?

PHPMailer can improve the security and functionality of email attachment handling in PHP by providing a more robust and secure way to send emails with attachments. It offers features like SMTP authentication, encryption, and attachment handling that can help prevent common security vulnerabilities in email handling.

// Include the PHPMailer library
require 'path/to/PHPMailer/src/PHPMailer.php';

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

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

// Add attachments to the email
$mail->addAttachment('path/to/file1.pdf', 'File1.pdf');
$mail->addAttachment('path/to/file2.jpg', 'File2.jpg');

// Set the email content
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Email with Attachments';
$mail->Body = 'Please find attached the files you requested.';

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