What is the purpose of using the mail() function in PHP to send emails with attachments?

The mail() function in PHP is used to send emails, but it does not support sending email attachments natively. To send emails with attachments using the mail() function, you can encode the attachment file as base64 and include it in the email message body. This allows you to send emails with attachments using the mail() function in PHP.

$to = 'recipient@example.com';
$subject = 'Email with Attachment';
$message = 'This is a test email with attachment.';
$filename = 'attachment.pdf';
$file = file_get_contents($filename);
$encoded_file = chunk_split(base64_encode($file));

$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=\"{$filename}\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"{$filename}\"\r\n\r\n";
$body .= $encoded_file . "\r\n";

$body .= "--{$boundary}--\r\n";

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