How can PHP beginners handle file attachments in emails, such as attaching a .txt file to an email?

To handle file attachments in emails using PHP, beginners can use the PHPMailer library. This library allows you to easily attach files to emails by specifying the file path, name, and type. First, install the PHPMailer library using Composer. Then, create a new PHP file and use the code snippet below to attach a .txt file to an email.

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

require 'vendor/autoload.php';

$mail = new PHPMailer();

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

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

$mail->Subject = 'Attachment Test';
$mail->Body = 'This is a test email with attachment.';

$mail->addAttachment('path/to/attachment.txt', 'attachment.txt', 'base64', 'text/plain');

if (!$mail->send()) {
    echo 'Error: ' . $mail->ErrorInfo;
} else {
    echo 'Email sent successfully';
}