Attach file php mail

Here is an example of how to attach a file to a PHP mail using the mail() function:

<?php

// Set the recipient's email address
$to = '[email protected]';

// Set the subject of the email
$subject = 'File Attachment Example';

// Set the message body
$message = 'This is an example email with a file attachment.';

// Set the file path and name
$file_path = 'path/to/file.txt';
$file_name = 'file.txt';

// Set the file type (e.g. text/plain, application/pdf, etc.)
$file_type = 'text/plain';

// Open the file and read its contents
$file = fopen($file_path, 'rb');
$file_contents = fread($file, filesize($file_path));
fclose($file);

// Set the email headers
$headers = array(
    'From' => '[email protected]',
    'Subject' => $subject,
    'MIME-Version' => '1.0',
    'Content-Type' => 'multipart/mixed'
);

// Create a boundary string
$boundary = '---------------------------'. uniqid();

// Add the message body to the email
$headers[] = 'Content-Type: text/plain; charset=UTF-8';
$headers[] = 'Content-Transfer-Encoding: 7bit';
$headers[] = 'Content-Disposition: inline';
$headers[] = 'X-Mailer: PHP/'. phpversion();

// Add the file attachment to the email
$headers[] = 'Content-Type: '. $file_type. '; name="'. $file_name. '"; filename="'. $file_name. '";';
$headers[] = 'Content-Transfer-Encoding: base64';
$headers[] = 'Content-Disposition: attachment; filename="'. $file_name. '";';

// Create the email message
$message = "This is a multi-part message in MIME format.\n\n".
           "--". $boundary. "\n".
           "Content-Type: text/plain; charset=UTF-8\n".
           "Content-Transfer-Encoding: 7bit\n\n".
           $message. "\n\n".
           "--". $boundary. "\n".
           "Content-Type: ". $file_type. "; name=\"". $file_name. "\"; filename=\"". $file_name. "\";\n".
           "Content-Transfer-Encoding: base64\n".
           "Content-Disposition: attachment; filename=\"". $file_name. "\";\n\n".
           chunk_split(base64_encode($file_contents)). "\n".
           "--". $boundary. "--";

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

?>

This code uses the mail() function to send an email with a file attachment. The file is read using the fopen() and fread() functions, and its contents are encoded using base64. The email headers are set using an array, and the message body is created using a combination of plain text and the file attachment.

Note that this is just an example, and you should adjust the code to fit your specific needs. Additionally, this code assumes that the file is located on the same server as the PHP script, and that the file path and name are correct. You may need to modify the code to accommodate different file locations or names.

Also, keep in mind that this is a basic example, and you may want to add more functionality to your email script, such as error handling, file validation, and security measures.