How can a user upload a file through an HTML form and have it sent as an attachment in an email using PHP?

To allow a user to upload a file through an HTML form and have it sent as an attachment in an email using PHP, you need to use the PHP `$_FILES` superglobal to handle the file upload, then use the PHPMailer library to send the email with the file attachment.

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

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $file = $_FILES['file']['tmp_name'];
    $mail = new PHPMailer(true);

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

        $mail->setFrom('your@example.com', 'Your Name');
        $mail->addAddress('recipient@example.com', 'Recipient Name');

        $mail->addAttachment($file, 'uploaded_file.txt');

        $mail->isHTML(true);
        $mail->Subject = 'File Attachment Test';
        $mail->Body = 'Please see the attached file.';

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