Are there any best practices for encoding and decoding binary data, such as PDF files, when sending them via email in PHP?

When sending binary data such as PDF files via email in PHP, it is important to encode the data properly to ensure it is transmitted correctly. One common method is to use base64 encoding to convert the binary data into a text format that can be safely sent via email. On the receiving end, the data can be decoded back into its original binary format.

// Encode binary data (PDF file) before sending via email
$pdfFile = 'path/to/pdf/file.pdf';
$pdfData = file_get_contents($pdfFile);
$encodedPdf = base64_encode($pdfData);

// Decode binary data received via email
$decodedPdf = base64_decode($encodedPdf);

// Example of sending an email with PDF attachment using PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

// Other email settings
$mail->addAttachment($pdfFile, 'attachment.pdf');
$mail->Body = 'Please find the PDF attachment below.';
$mail->send();