What are best practices for handling email attachments in PHP to ensure successful delivery?

When handling email attachments in PHP, it is important to ensure that the attachments are properly encoded and added to the email message before sending. One common issue is that attachments may not be delivered successfully if they are not encoded correctly. To solve this, you can use the PHPMailer library which provides a simple and reliable way to handle email attachments in PHP.

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

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

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

// Set up the email parameters
$mail->isMail();
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Email with Attachment';
$mail->Body = 'This email contains an attachment.';

// Add attachment
$file_path = '/path/to/attachment/file.pdf';
$mail->addAttachment($file_path);

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