How to send upload file in mail in php

To send an uploaded file in an email using PHP, you can use the mail() function or a PHP mail library like PHPMailer. Here's an example using mail():

Example 1: Using mail()

<?php
// Assume you have a form with a file input field named "file"
if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $filename = $file['name'];
    $filetype = $file['type'];
    $filetmp = $file['tmp_name'];

    // Set email headers
    $headers = 'From: Your Name <[email protected]>'. "\r\n";
    $headers.= 'Content-Type: multipart/mixed; boundary="boundary"'. "\r\n";

    // Set email body
    $body = "File attached: $filename\r\n";
    $body.= "--boundary\r\n";
    $body.= "Content-Type: $filetype; name=\"$filename\"\r\n";
    $body.= "Content-Transfer-Encoding: base64\r\n";
    $body.= "Content-Disposition: attachment; filename=\"$filename\"\r\n\r\n";
    $body.= chunk_split(base64_encode(file_get_contents($filetmp)));

    // Send email
    mail('[email protected]', 'File Upload', $body, $headers);
}
?>

In this example, we use the mail() function to send an email with the uploaded file attached. We set the email headers to include the Content-Type and Content-Disposition headers, which specify the file type and attachment. We then use the chunk_split() and base64_encode() functions to encode the file contents and split them into chunks for sending.

Example 2: Using PHPMailer

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

// Assume you have a form with a file input field named "file"
if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $filename = $file['name'];
    $filetype = $file['type'];
    $filetmp = $file['tmp_name'];

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

    // Set email sender and recipient
    $mail->setFrom('[email protected]');
    $mail->addAddress('[email protected]');

    // Set email subject
    $mail->Subject = 'File Upload';

    // Set email body
    $body = "File attached: $filename";

    // Add attachment
    $mail->addAttachment($filetmp, $filename, $filetype);

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

In this example, we use the PHPMailer library to send an email with the uploaded file attached. We create a new PHPMailer object and set the email sender, recipient, subject, and body. We then add the attachment using the addAttachment() method and send the email using the send() method.

Remember to replace the placeholders ([email protected], [email protected]) with your actual email addresses.