What are some potential issues with using the mail() function in PHP when sending emails with attachments?

One potential issue with using the mail() function in PHP when sending emails with attachments is that the attachments may not be properly encoded, leading to corrupted files or unreadable content for the recipient. To solve this issue, you can use the PHPMailer library, which provides a more robust and reliable way to send 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 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('from@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 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
?>