Saturday, March 17, 2012

PHP Script for sending mail with attachment file

send email with attachment in php 


code to send email with attachment in php 


form.html



<form action="sendmail.php" >
<label> Name:</label>
<input type="text" name="name" id="name" />
<label> email:</label>
<input type="text" name="email" id="email" />
<label> Phone No:</label>
<input type="text" name="ph" id="ph" />
<label> Message:</label>
<input type="text" name="msg" id="msg" />
<label> Resume :</label>
<input type="file" name="txtresume" id="txtresume" />
<input type="submit" name="send mail" value="send mail"  />
</form>




sendmail.php


<?php
error_reporting
(0);

//ini_set('display_errors','off');
//ini_set('memory_limit', '-1');


 
if(isset($_POST) && !empty ($_POST["name"]) ){
$files = array($_FILES["txtresume"]["tmp_name"]); 

// txtresume input type = file name =txtresume
 
$files1 = array($_FILES["txtresume"]["name"]);

$name $_POST['name']; 

$email $_POST['email']; 
$ph $_POST['ph'];
$msg $_POST['msg']; 
$subject " Resume ";
 
$message1 "Name: " $name "<br> Phone No: " $ph"<br/>Email Id:".$email "<br/>Message Details : " $msg  ;

 
$headers "From: $email";
// boundary

$semi_rand md5(time()); $mime_boundary "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment

$headers .= "\nMIME-Version: 1.0\n" "Content-Type: multipart/mixed;\n" " boundary=\"{$mime_boundary}\"";

// multipart boundary 



$message "This is a multi-part message in MIME format.\n\n" "--{$mime_boundary}\n" "Content-Type: text/html; charset=\"iso-8859-1\"\n" "Content-Transfer-Encoding: 7bit\n\n" $message1 "\n\n"; $message .= "--{$mime_boundary}\n"

// preparing attachments 

for($x=0;$x<count($files);$x++){
 
$file fopen($files[$x],"rb");
 
$data fread($file,filesize($files[$x]));
 
fclose($file);
 
$data chunk_split(base64_encode($data)); 


 
$message .= "Content-Type: {\"application/octet-stream\"};\n" " name=\"$files1[$x]\"\n" .
 
"Content-Disposition: attachment;\n" " filename=\"$files1[$x]\"\n" .
 
"Content-Transfer-Encoding: base64\n\n" $data "\n\n";
 
$message .= "--{$mime_boundary}\n";
}
//echo $message ;
 
$to 'rajeevphp2011@gmail.com';
if(
mail($to $subject $message $headers )){

echo 
' Successfully Send';

} else {

echo 
' Please Try Agein ';

}
}
echo 
' invalid data'; ?>


2 comments:

  1. Dear sir,
    While using this code it shows "invalid data" what to do?
    Regard,
    M G

    ReplyDelete
  2. thanks for this script, it really worked for me

    ReplyDelete

If you Satisfied , Please Leave a comment