How can base64 encoding be utilized in PHP to properly save and handle email attachments?

When handling email attachments in PHP, it is important to encode the attachments in base64 before sending them via email. This ensures that the attachments are properly encoded and can be decoded by the recipient. To achieve this, you can use the base64_encode() function to encode the attachment data before adding it to the email.

// Sample code to encode and attach a file using base64 encoding in PHP

// Path to the file to be attached
$file_path = 'path/to/attachment/file.pdf';

// Read the file content
$file_content = file_get_contents($file_path);

// Encode the file content in base64
$encoded_content = base64_encode($file_content);

// Create the attachment for the email
$attachment = chunk_split($encoded_content);

// Add the attachment to the email
$mail->addAttachment($attachment, 'file.pdf', 'base64', 'application/pdf');