How to send file in mail in php

To send a file in an email using PHP, you can use the mail() function or a PHP mail library such as PHPMailer. Here's an example of how to do it using the mail() function:

<?php
// Define the recipient's email address
$to = '[email protected]';

// Define the subject of the email
$subject = 'File attachment';

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

// Define the email body
$body = 'This is the email body.';

// 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 = 'From: [email protected]'. "\r\n".
           'Reply-To: [email protected]'. "\r\n".
           'MIME-Version: 1.0'. "\r\n".
           'Content-Type: multipart/mixed; boundary="This is the boundary string"';

// Create the email body
$email_body = "This is the email body.\r\n\r\n";
$email_body.= '--This is the boundary string'. "\r\n".
               'Content-Type: application/octet-stream; name="'. $file_name. '"'. "\r\n".
               'Content-Disposition: attachment; filename="'. $file_name. '"'. "\r\n".
               $file_contents. "\r\n".
               '--This is the boundary string--';

// Send the email
mail($to, $subject, $email_body, $headers);
?>

In this example, the mail() function is used to send an email with a file attachment. The file is read using the fopen() and fread() functions, and its contents are included in the email body.

The email headers are set using the Content-Type and Content-Disposition headers to specify that the file is an attachment. The boundary string is used to separate the email body from the file attachment.

You can also use PHPMailer library to send email with attachment, here is an example:

<?php
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();

$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');

$mail->Subject = 'File attachment';
$mail->Body = 'This is the email body.';

$file_path = 'path/to/file.txt';
$file_name = 'file.txt';

$mail->addAttachment($file_path, $file_name);

if (!$mail->send()) {
    echo 'Error: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully';
}
?>

In this example, the PHPMailer library is used to send an email with a file attachment. The addAttachment() method is used to add the file to the email. The setFrom() and addAddress() methods are used to set the sender and recipient of the email, respectively. The Subject and Body properties are used to set the subject and body of the email, respectively.