Attach and sent mail in php

Here is an example of how to attach a file and send an email using PHP:

Step 1: Set up the email headers and body

<?php
// Set the email headers
$headers = 'From: [email protected]'. "\r\n".
           'Reply-To: [email protected]'. "\r\n".
           'MIME-Version: 1.0'. "\r\n".
           'Content-Type: text/html; charset=UTF-8';

// Set the email body
$body = 'This is the email body';

// Set the email subject
$subject = 'Test Email with Attachment';

// Set the email recipient
$to = '[email protected]';
?>

Step 2: Attach the file

<?php
// Set the file path and name
$file_path = 'path/to/your/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 attachment headers
$attachment_headers = 'Content-Type: '. $file_type. '; name="'. $file_name. '"'. "\r\n".
                       'Content-Disposition: attachment; filename="'. $file_name. '"'. "\r\n".
                       'Content-Length: '. strlen($file_contents). "\r\n";

// Add the attachment to the email body
$body.= "\r\n\r\n". $attachment_headers. "\r\n". $file_contents;
?>

Step 3: Send the email

<?php
// Send the email using the mail() function
mail($to, $subject, $body, $headers);
?>

Full code

Here is the full code example:

<?php
// Set the email headers
$headers = 'From: [email protected]'. "\r\n".
           'Reply-To: [email protected]'. "\r\n".
           'MIME-Version: 1.0'. "\r\n".
           'Content-Type: text/html; charset=UTF-8';

// Set the email body
$body = 'This is the email body';

// Set the email subject
$subject = 'Test Email with Attachment';

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

// Set the file path and name
$file_path = 'path/to/your/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 attachment headers
$attachment_headers = 'Content-Type: '. $file_type. '; name="'. $file_name. '"'. "\r\n".
                       'Content-Disposition: attachment; filename="'. $file_name. '"'. "\r\n".
                       'Content-Length: '. strlen($file_contents). "\r\n";

// Add the attachment to the email body
$body.= "\r\n\r\n". $attachment_headers. "\r\n". $file_contents;

// Send the email using the mail() function
mail($to, $subject, $body, $headers);
?>

Note: Make sure to replace the placeholders ([email protected], [email protected], path/to/your/file.txt, etc.) with your actual email address, recipient email address, and file path. Also, make sure to adjust the file type and name as needed.