How can base64 encoding be utilized to send file attachments in PHP emails?

When sending file attachments in PHP emails, the files need to be encoded in base64 format before being included in the email. This ensures that the file content is properly transferred and received by the recipient. The base64_encode() function in PHP can be used to encode the file content before adding it as an attachment to the email.

// File to be attached
$file_path = 'path/to/file.pdf';
$file_name = 'file.pdf';

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

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

// Create the email message
$subject = 'Email with Attachment';
$message = 'Please see the attached file.';
$boundary = md5(time());

$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$boundary."\"\r\n";

$body = "--".$boundary."\r\n";
$body .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= $message."\r\n";

$body .= "--".$boundary."\r\n";
$body .= "Content-Type: application/pdf; name=\"".$file_name."\"\r\n";
$body .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= $encoded_content."\r\n";

$body .= "--".$boundary."--";

// Send the email
mail('recipient@example.com', $subject, $body, $headers);