What are some best practices for handling file attachments in PHP mail scripts?

When handling file attachments in PHP mail scripts, it is important to properly encode the attachment data, set the appropriate headers, and ensure that the file size does not exceed any server limits. One common method for handling file attachments is to use the PHPMailer library, which simplifies the process of sending emails with attachments.

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

require 'vendor/autoload.php';

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

// Set up the email parameters
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Attachment Test';
$mail->Body = 'Please see the attached file.';

// Add the attachment
$file_path = 'path/to/file.pdf';
$mail->addAttachment($file_path);

// Send the email
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}