Wednesday, May 18, 2016

Attachment Mail using PHP



<?php
if($_POST && isset($_FILES['dac_file']))
{

    $from_email = $_POST["fromcomp"];
    $subject = $_POST["subject"];
    $message = $_POST["msg"];
 
    //get file details we need
    $file_tmp_name    = $_FILES['dac_file']['tmp_name'];
    $file_name        = $_FILES['dac_file']['name'];
    $file_size        = $_FILES['dac_file']['size'];
    $file_type        = $_FILES['dac_file']['type'];
    $file_error       = $_FILES['dac_file']['error'];
 
    $user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);

    if($file_error>0)
    {
        die('upload error');
    }
    $handle = fopen($file_tmp_name, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $encoded_content = chunk_split(base64_encode($content));


        $boundary = md5("sanwebe");
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:".$from_email."\r\n";
        $headers .= "Reply-To: ".$user_email."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
     
        //plain text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($message));
     
        //attachment
        $body .= "--$boundary\r\n";
        $body .="Content-Type: $file_type; name=\"$file_name\"\r\n";
        $body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
        $body .="Content-Transfer-Encoding: base64\r\n";
        $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
        $body .= $encoded_content;
 
    $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if($sentMail)
    {    
        die('Thank you for your email');
    }else{
        die('Could not send mail! Please check your PHP mail configuration.');
    }

}
?>
<form name="form1" enctype="multipart/form-data" method="post" action="">
<label>From Mail
<input type="email" name="fromcomp" />
</label>
<label>Your Name
<input type="text" name="name" />
</label>
<label>Subject
<input type="text" name="subject" />
</label>
<label>Message
<input type="text" name="msg" />
</label>
<label>Attachment
<input type="file" name="dac_file" />
</label>
<label>
<input type="submit" name="button" value="Submit" />
</label>
</form>

No comments:

Post a Comment

Dharamart.blogspot.in