Are there any best practices for encoding file attachments in PHP emails?

When sending emails with file attachments in PHP, it is important to encode the attachments properly to ensure they are correctly received by the recipient. One common method for encoding file attachments is using base64 encoding. This ensures that the file data is converted into a text format that can be safely transmitted via email.

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

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

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

// Set the email headers
$attachment = "Content-Type: application/octet-stream; name=\"" . basename($file_path) . "\"\r\n";
$attachment .= "Content-Transfer-Encoding: base64\r\n";
$attachment .= "Content-Disposition: attachment; filename=\"" . basename($file_path) . "\"\r\n\r\n";
$attachment .= $encoded_content;

// Send email with attachment
$to = 'recipient@example.com';
$subject = 'Email with Attachment';
$message = 'Please see the attached file.';
$headers = 'From: sender@example.com' . "\r\n" .
    'Reply-To: sender@example.com' . "\r\n" .
    'MIME-Version: 1.0' . "\r\n" .
    'Content-Type: multipart/mixed; boundary="boundary"' . "\r\n\r\n" .
    '--boundary' . "\r\n" .
    'Content-Type: text/plain; charset="utf-8"' . "\r\n" .
    'Content-Transfer-Encoding: 7bit' . "\r\n\r\n" .
    $message . "\r\n\r\n" .
    '--boundary' . "\r\n" .
    $attachment . "\r\n" .
    '--boundary--';

mail($to, $subject, '', $headers);