How to send attachment in mail using php mail function

To send an attachment in an email using the PHP mail() function, you can use the following approach:

  1. First, you need to specify the attachment file path and name in the mail() function's additional_headers parameter.
  2. Use the Content-Type header to specify the type of the attachment (e.g., application/octet-stream for a binary file).
  3. Use the Content-Disposition header to specify the attachment's disposition (e.g., attachment to indicate that it's an attachment).
  4. Use the Content-Transfer-Encoding header to specify the encoding of the attachment (e.g., base64 to encode the attachment).

Here's an example code snippet that demonstrates how to send an attachment using the mail() function:

<?php
$to = '[email protected]';
$subject = 'Test Email with Attachment';
$message = 'This is a test email with an attachment.';

// Specify the attachment file path and name
$attachment = 'path/to/attachment/file.txt';

// Set the email headers
$headers = array(
    'From' => '[email protected]',
    'To' => $to,
    'Subject' => $subject,
    'Content-Type' => 'multipart/mixed',
    'Content-Disposition' => 'attachment; filename="'. basename($attachment). '"',
    'Content-Transfer-Encoding' => 'base64'
);

// Read the attachment file
$attachment_file = file_get_contents($attachment);

// Send the email
mail($to, $subject, $message, implode("\r\n", $headers), $attachment_file);
?>

In this example, the mail() function is called with the following parameters:

Note that the mail() function returns a boolean value indicating whether the email was sent successfully. You can use this value to determine whether the email was sent correctly.

Also, keep in mind that the mail() function is a low-level function that requires you to specify the email headers and body manually. If you need more advanced email functionality, such as sending HTML emails or handling attachments with different types, you may want to consider using a PHP email library or framework, such as PHPMailer or SwiftMailer.