How to send file using mail function

To send a file using the mail function in PHP, you can use the addAttachment method. Here is an example:

<?php

$to = '[email protected]';
$subject = 'File attachment';
$message = 'This is a test message';

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

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

// Create a new PHPMailer object
$mail = new PHPMailer();

// Set the email body
$mail->Body = $message;

// Add the file attachment
$mail->AddAttachment($file_path, $file_name);

// Set the recipient email address
$mail->AddAddress($to);

// Send the email
$mail->Send();

?>

In this example, we create a new PHPMailer object and set the email body, subject, and recipient email address. We then use the AddAttachment method to add the file to the email. Finally, we use the Send method to send the email.

You can also use the mail function to send a file attachment, but it's more complex and less flexible than using the PHPMailer class. Here is an example:

<?php

$to = '[email protected]';
$subject = 'File attachment';
$message = 'This is a test message';

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

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

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

// Set the email body
$headers.= "\r\n\r\n". $boundary. "\r\n";
$headers.= 'Content-Type: text/plain; charset=UTF-8'. "\r\n";
$headers.= 'Content-Disposition: inline'. "\r\n";
$headers.= 'Content-Transfer-Encoding: 7bit'. "\r\n";
$headers.= "\r\n". $message. "\r\n";

// Add the file attachment
$headers.= "\r\n\r\n". $boundary. "\r\n";
$headers.= 'Content-Type: application/octet-stream; name="'. $file_name. '"'. "\r\n";
$headers.= 'Content-Disposition: attachment; filename="'. $file_name. '"'. "\r\n";
$headers.= 'Content-Transfer-Encoding: base64'. "\r\n";
$headers.= "\r\n". chunk_split(base64_encode(file_get_contents($file_path))). "\r\n";

// Send the email
mail($to, $subject, '', $headers);

?>

In this example, we create a boundary string and use it to separate the email body and the file attachment. We then use the mail function to send the email.

Note that the mail function is not as flexible as the PHPMailer class, and it may not work as well with all email providers.