How can files be attached to emails using the mail() function in PHP?

To attach files to emails using the mail() function in PHP, you need to use the MIME (Multipurpose Internet Mail Extensions) standard to encode the file data and include it in the email headers. This involves setting the Content-Type and Content-Disposition headers appropriately. Additionally, you need to read the file data and encode it using base64_encode() before including it in the email.

$to = 'recipient@example.com';
$subject = 'Email with attachment';
$message = 'This is a test email with attachment.';
$file_path = '/path/to/attachment.pdf';
$file_name = 'attachment.pdf';
$file_data = file_get_contents($file_path);
$encoded_file_data = chunk_split(base64_encode($file_data));

$boundary = md5(uniqid(time()));

$headers = "From: sender@example.com\r\n";
$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_file_data . "\r\n";

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

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