Codeconia -Learn Programming

HTML Form to Email with Attachment using PHP

Hello everyone for the big support my HTML form to PHP mail post. As per my subscriber’s request, I made this new tutorial. to send any attachment via HTML form to the email we can use phpmail function. here is am giving an example of how to do it.

The HTML form

<form action="mail.php" method="post" enctype="multipart/form-data">
    <input type="text" name="name" placeholder="Name"> <br>
    <input type="text" name="email" placeholder="email"> <br>
    <input type="text" name="message" placeholder="Message"> <br>
    <input type="file" name="file"> <br>
    <input type="submit" value="Submit">
</form>

mail.php file

<?php

    $filenameee =  $_FILES['file']['name'];
    $fileName = $_FILES['file']['tmp_name']; 
    $name = $_POST['name'];
    $email = $_POST['email'];
    $usermessage = $_POST['message'];
    
    $message ="Name = ". $name . "\r\n  Email = " . $email . "\r\n Message =" . $usermessage; 
    
    $subject ="My email subject";
    $fromname ="My Website Name";
    $fromemail = '[email protected]';  //if u dont have an email create one on your cpanel

    $mailto = '[email protected]';  //the email which u want to recv this email




    $content = file_get_contents($fileName);
    $content = chunk_split(base64_encode($content));

    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (RFC)
    $eol = "\r\n";

    // main header (multipart mandatory)
    $headers = "From: ".$fromname." <".$fromemail.">" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;

    // message
    $body = "--" . $separator . $eol;
    $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $body .= "Content-Transfer-Encoding: 8bit" . $eol;
    $body .= $message . $eol;

    // attachment
    $body .= "--" . $separator . $eol;
    $body .= "Content-Type: application/octet-stream; name=\"" . $filenameee . "\"" . $eol;
    $body .= "Content-Transfer-Encoding: base64" . $eol;
    $body .= "Content-Disposition: attachment" . $eol;
    $body .= $content . $eol;
    $body .= "--" . $separator . "--";

    //SEND Mail
    if (mail($mailto, $subject, $body, $headers)) {
        echo "mail send ... OK"; // do what you want after sending the email
        
        
    } else {
        echo "mail send ... ERROR!";
        print_r( error_get_last() );
    }

      

Check out the video for more details and to know how to implement this

Ajith Jojo

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular