How to attached file with mail in php

In PHP, you can attach a file to an email using the mail() function or a PHP mail library such as PHPMailer. Here are some examples:

Using the mail() function:

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

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

// Read the file contents
$file_contents = file_get_contents($file_path);

// Set the email headers
$headers = 'From: [email protected]'. "\r\n".
           'Content-Type: text/plain; charset=UTF-8'. "\r\n".
           'Content-Disposition: attachment; filename="'. $file_name. '"';

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

In this example, we use the file_get_contents() function to read the file contents and then set the email headers to include the file name and attachment type. The mail() function is then used to send the email with the attachment.

Using PHPMailer:

<?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 a test email with an attachment.';

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

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

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

In this example, we use the PHPMailer library to create a new email object and set the email headers and body. We then use the addAttachment() method to add the file attachment and finally send the email using the send() method.

Note: Make sure to replace the placeholders (path/to/your/file.txt, [email protected], your_password, etc.) with your actual file path, email address, and password.