Is it better to use a pre-existing solution like PHPMailer or create a custom solution for handling file attachments in PHP form mailers?

When handling file attachments in PHP form mailers, it is generally better to use a pre-existing solution like PHPMailer. PHPMailer is a widely-used library that simplifies the process of sending emails with attachments, handling MIME types, and ensuring proper encoding. By using PHPMailer, you can save time and effort in developing a custom solution while also benefiting from the library's robust features and ongoing support.

<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

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

// Set up the SMTP server 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('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');

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

// Set the email subject and body
$mail->Subject = 'Email with attachments';
$mail->Body = 'Please find the attached files';

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