What are some best practices for handling email attachments in PHP when sending emails?

When sending emails with attachments in PHP, it is important to handle the attachments properly to ensure they are sent successfully. One best practice is to use the PHPMailer library, which simplifies the process of sending emails with attachments. By using PHPMailer, you can easily add attachments to your emails and ensure they are encoded correctly for delivery.

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

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

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

// Set up the SMTP 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 see the attached files.';

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