Menu

Send Email with Attachment in PHP, Send Attachment in Email in PHP

PHP, Tech-Byte, Tips By Dec 19, 2012 192 Comments

Send Email Attachment in PHP


Hello friends today i am going to provide a tutorial regarding how to send email attachment in PHP. For a normal mail sending you can visit my previous article in which you will learn how to send mail in php how to send email in php In this tutorial you will get the whole code and its really a very short code to send the attachment. Sending an email attachment in php is not an easy task many time you will get the errors like file is of 0 kb, file name is something else, email is delivered but no you dont get the mail etc. In this tutorial / Example you will get he procedure of how to send the email attachment in php.

Demo Link

Things we need to send email attachment in php

  • HTML Form
  • PHP Code

Email sending HTML Form

First we will start with the html for. In html form we will use the these text fields

  • To – On which mail is delivered
  • Message – Message which is to be delivered
  • Subject – Subject for the Email
  • Attachment – Email attachment which you want to send

Below is the HTML code for email sending

<form id="attach" name="attach" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data">
<table>
<tr>
<td>To</td><td>:</td><td><input type="text" name="to" id="to"></td>
</tr>
<tr>
<td>Subject</td><td>:</td><td><input type="text" name="subject" id="subject"></td>
</tr>
<tr>
<td>Message</td><td>:</td><td><input type="text" name="msg" id="msg"></td>
</tr>
<tr>
<td>Attachment<span class="imp">*</span></td><td>:</td><td><input type="file" name="upload" id="upload"></td>
</tr>
<tr>
<td></td><td></td><td><input type="submit" value="Submit" id="send" name="send"></td>
</tr>
</table>
 </form>

Now we have finished with our html form. Lets move to our PHP code

Email attachment php code

Here will write the PHP code for the attachment sending with the help of php.


First we will receive our data and retain that data below is the code

$upload_name=$_FILES["upload"]["name"];
$upload_type=$_FILES["upload"]["type"];
$upload_size=$_FILES["upload"]["size"];
$upload_temp=$_FILES["upload"]["tmp_name"];
$message=$_POST["msg"];
$subject = $_POST["subject"];
$to=$_POST["to"];

Now we will send the email with attachment in php

if(isset ($_POST["send"]))
 {
    $upload_name=$_FILES["upload"]["name"];
    $upload_type=$_FILES["upload"]["type"];
    $upload_size=$_FILES["upload"]["size"];
    $upload_temp=$_FILES["upload"]["tmp_name"];
    $message=$_POST["msg"];
    $subject = $_POST["subject"];
    $to=$_POST["to"];

    if($message==""||$subject==""||$to=="")
    {
        echo '<font style="font-family:Verdana, Arial; font-size:11px; color:#F3363F; font-weight:bold">Please fill all fields</font>';
    }
    else
    {
        $fp = fopen($upload_temp, "rb");
    $file = fread($fp, $upload_size);

    $file = chunk_split(base64_encode($file));
    $num = md5(time());

        //Normal headers

    $headers  = "From: Info Mail<vivek@simplyitsols.com>\r\n";
       $headers  .= "MIME-Version: 1.0\r\n";
       $headers  .= "Content-Type: multipart/mixed; ";
       $headers  .= "boundary=".$num."\r\n";
       $headers  .= "--$num\r\n";

        // This two steps to help avoid spam

    $headers .= "Message-ID: <".gettimeofday()." TheSystem@".$_SERVER['SERVER_NAME'].">\r\n";
    $headers .= "X-Mailer: PHP v".phpversion()."\r\n";

        // With message

    $headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
       $headers .= "Content-Transfer-Encoding: 8bit\r\n";
       $headers .= "".$message."\n";
       $headers .= "--".$num."\n";

        // Attachment headers

    $headers  .= "Content-Type:".$upload_type." ";
       $headers  .= "name=\"".$upload_name."\"r\n";
       $headers  .= "Content-Transfer-Encoding: base64\r\n";
       $headers  .= "Content-Disposition: attachment; ";
       $headers  .= "filename=\"".$upload_name."\"\r\n\n";
       $headers  .= "".$file."\r\n";
       $headers  .= "--".$num."--";
    // SEND MAIL
       @mail($to, $subject, $message, $headers);
     fclose($fp);

    echo '<font style="font-family:Verdana, Arial; font-size:11px; color:#333333; font-weight:bold">Attachment has been sent Successfully.<br /></font>';
 }
 }

From the above demo you can check this or click the below link to check it on separate page. Below is the working code you can download it also.

Author

Hello i am Vivek Moyal PHP developer and writes tutorials for students and beginners. Love to explore new cities

192 Comments

  1. Akshay Gupta says:

    Thanks Vivek, I was able to sending mail with attachment by using the code.

  2. rakhi says:

    Demo is not working

  3. I am using windows sir, I am also getting the same problem

  4. I actually have the same problem with the other commenters, I used your code but there was no mail.

    1. Vivek Moyal says:

      Which hosting you are using Linux or Windows

  5. bhuvaneswari.s says:

    haaii,.. its not working.. i got a success mail message.. bt i could not get any mail.

  6. jothy says:

    Hi, Vivek.. i’m also using this code. mail sent message displayed , but i dont have received any other mail and attachements. pls help me.. thanks in advance…

  7. arvind says:

    vivek sir thanx for provide the code……………………….
    but i a have problem …
    the file attach properly but it size 0 bite…….
    plz help me…………. i m wait your replay

  8. gayatri gore says:

    Thank you so much for this tutorial.
    I have use your code, it sent attachments successfully, but there message body is empty.
    Can you please help me for this problem.
    I am testing it on Linux hosting.
    Please help me for this.
    Thanks in advance.

    1. Vivek Moyal says:

      Please check when you submit the script you are getting the text in mail body variable.

      1. sidhi says:

        help i also didnot get mail

    2. arvind says:

      same problems
      me… the resume upload successful but its size 0 byte

      1. Vivek Moyal says:

        Which hosting you are using linux or windows

  9. parminder says:

    thanks bro…. thank you very much…. your are the best

  10. Sridhar K says:

    Hi Vivek Sir,

    i

  11. manohar says:

    Your The Best Dude..ThankYou

  12. maria says:

    ehen i run you demo http://vivekmoyal.in/testing/emailAttachment.php it works .. even i got email with attachment .. but when i apply this code in my file .. no mail .. 🙁

    1. Vivek Moyal says:

      Which hosting platform you are using …. windows or linux

  13. maria says:

    i just download you code file and run .. but i get no mail …..

  14. skm says:

    thank you very much.

  15. Vivek thank you very much… This is an excellent code…

  16. Rajesh says:

    <?php

    if ($_SERVER['REQUEST_METHOD']=="POST"){
    //require('PHPMailer/class.phpmailer.php');
    // CHANGE THE TWO LINES BELOW

    $email_to = "rajesh99hosters@gmail.com";

    $email_subject = "Job Applicant Information";

    $name = $_POST['name']; // required
    $email_from = $_POST['email']; // required
    $contact_no = $_POST['contact_no']; // required
    $visa_status = $_POST['visa_status']; // required
    $skill_set = $_POST['skill_set']; // required
    $country_name = $_POST['country_name']; // required

    //if(is_uploaded_file($_FILES["image"]["name"])
    if(move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $_FILES["image"]["name"]))
    {

    $path="/upload/" . $_FILES["image"]["name"];
    $file=fopen($path,'r');
    $content = fread( $file, filesize($path));
    $attachment = chunk_split(base64_encode(file_get_contents($file)));
    }
    else
    {
    echo "alert(‘Invalid file’)”;
    }
    if($country_name=1)
    {
    $country_name=$_POST[‘state’].”\n”;
    $country_name.=$_POST[‘city’].”\n”;
    }
    if($country_name=2)
    {
    $country_name=$_POST[‘country1’].”\n”;
    $country_name.=$_POST[‘state1’].”\n”;
    $country_name.=$_POST[‘city1’].”\n”;
    }

    $email_message = “Form details below.\n\n”;

    $email_message .= “Name: “.$name.”\n”;
    $email_message .= “Email: “.$email_from.”\n”;
    $email_message .= “Contact Number: “.$contact_no.”\n”;
    $email_message .= “Visa Status: “.$visa_status.”\n”;
    $email_message .= “Skillset: “.$skill_set.”\n”;
    $email_message .= “Location: “.$country_name.”\n”;
    $email_message .= “Resume: “.$attachment.”\n”;

    // create email headers
    $headers = ‘From: ‘.$email_from.”\r\n”.’Reply-To: ‘.$email_from.”\r\n” .’X-Mailer: PHP/’ . phpversion();
    //$headers .= ‘Resume: ‘.$attachment.”\r\n”;

    @mail($email_to, $email_subject, $email_message, $headers);

    header(‘Location:job_apply.php’);

    }
    ?>

    what is the mistake in my code plz see my above code
    mail is sending at the same time file was uploaded to target location but file is not sending

    1. Vivek Moyal says:

      Which hosting you are using linux or windows

  17. siva says:

    Hello sir,

    These php mail sending with an attachment is really useful, but i have some doubts on this, if i use pearl to mail sending? in this case i tried lot, but i cant send a attachment except attachment links , can you help me? and another thing i checked your demo, the mails are going to store in spam, wherefore?

    1. Vivek Moyal says:

      In script i am using a wrong mail id thats y it is going in spam. The from mail id should be in format id@domainname.com than it will not go in spam

  18. dipa says:

    Yes sir I am checking inbox and spam there is no any email ,that I was sending from my email id.Sir any changes in php.ini file?.

    1. Vivek Moyal says:

      Ok …. tell me these too….. Are you using it on localhost or over the server/online. If you are using it online than what is your hosting platform. Windows or Linux. As this code will work only with linux.

  19. codeblank says:

    @shri +1

    Im getting the same issue not only Outlook but also on Thunderbird. Do you have any fix now @Vivek?

    Thanks for the share though

    1. Vivek Moyal says:

      Try to put \n at the end of the message than try. I read somewhere that putting \n will solve this problem

  20. shri says:

    hi
    your code is working fine for gmail but when i tested it for outlook the email message was not there & only attachment was there when i opened the attachment the mail message content was there in attachment & original attachment content was gone can u tell me why is this happening & how can i fix this

    1. Vivek Moyal says:

      For outlook i have never used it. I cant say anything about it….. speechless

  21. Jay says:

    code works fine in my host gator hosting panel. but when i attached code with different hosting panel isn’t working wall. in this panel mail function code work wall without attachment. can you pls help me to fix that.

    1. Vivek Moyal says:

      Sometime it depends on the hosting provider. And one more thing that it will not work with the windows hosting. If you are working with the widows hosting than you will get the mail but i think you will have issues with the attachment

      1. Jay says:

        thanks for reply

        but i am using papahosting Linux hosting server.

        1. Vivek Moyal says:

          Than try to contact with your hosting provider may be they are blocking the script

  22. can you say me how to upload multiple attachment and send it using php

  23. swapnil says:

    code works fine….but my mailer shows attachment of 0 byte.please tell me what i have to do so that i get proper attachment.

  24. Hey there are using WordPress for your site platform? I’m new to
    the blog world but I’m trying to get started and create my own.
    Do you require any html coding knowledge to make your own
    blog? Any help would be really appreciated!

  25. venkatarao says:

    successfully mail send along with attachment ,but when download that image it shoe like this
    (” iVBORw0KGgoAAAANSUhEUgAAASwAAAFeCAYAAAA/lyK/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAK T2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AU kSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXX Pues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgAB eNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAt AGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3 AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dX Lh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+ 5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk 5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd 0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA 4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzA BhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/ph CJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5 h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+ “)

  26. rohit shukla says:

    Hello sir i m a php beginer i want to send mail to gmail or hotmail account from my script on localhost when i cnnct it with internet….plz sir help me

    1. Vivek Moyal says:

      I can help you with the error in your code….. I cant make a code for you like this. If you have any issue in your code than let me know

  27. john says:

    Sir,

    Hoping that you can help me because I need a code for my site that automatically send to may email the attachment.

    To all buddies out there hoping for kind consideration

  28. john says:

    Sir i want to use this code but i want to know what i should be name of html and the php hehe 🙂

  29. Bikash patra says:

    100% success this Code .. Try This

    <form method="post" action="” id=”uploadform” enctype=”multipart/form-data” >

    Name * <input class="textbox"type="text" value="” autofocus required=”true” name=”namefrom” tabindex=”1″>
    Email * <input class="textbox"type="text" autofocus required="true" value="” name=”emailfrom” tabindex=”2″ >
    Affiliations * <input class="textbox"type="text" autofocus required="true" name="affilations" tabindex="3" value="”>
    Post * <input class="textbox"type="text" autofocus required="true" name="postt" tabindex="4" value="”>
    Attach file *

    File Upload:(1 file only, max file size 1024kb. Allowed file formats are .doc, .pdf, .zip, .rar, .png)

    Sent

    <?php
    }

    // enquiry form validation

    function process_form() {
    // Read POST request params into global vars
    // FILL IN YOUR EMAIL
    $to = "bikash@verijanus.in";
    $subject = "Attach Mail Documents";
    //$subject = trim($_POST['subject']);
    $namefrom = trim($_POST['namefrom']);
    $affilations = trim($_POST['affilations']);
    $postt = trim($_POST['postt']);
    $emailfrom = trim($_POST['emailfrom']);
    //$comments = trim($_POST['comments']);

    // Allowed file types. add file extensions WITHOUT the dot.
    $allowtypes=array("zip", "rar", "doc", "pdf", "png");

    // Require a file to be attached: false = Do not allow attachments true = allow only 1 file to be attached
    $requirefile="true";

    // Maximum file size for attachments in KB NOT Bytes for simplicity. MAKE SURE your php.ini can handel it,
    // post_max_size, upload_max_filesize, file_uploads, max_execution_time!
    // 2048kb = 2MB, 1024kb = 1MB, 512kb = 1/2MB etc..
    $max_file_size="1024";

    // Thank you message
    $thanksmessage="Your email has been sent, we will respond shortly.";

    $errors = array(); //Initialize error array

    //checks for a name
    if (empty($_POST['namefrom']) ) {
    $errors[]='You forgot to enter your name';
    }

    //checks for an email
    if (empty($_POST['emailfrom']) ) {
    $errors[]='You forgot to enter your email';
    } else {

    if (!eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['emailfrom'])))) {
    $errors[]='Please enter a valid email address';
    } // if eregi
    } // if empty email

    //checks for a subject
    if (empty($_POST['affilations']) ) {
    $errors[]='You forgot to enter a subject';
    }

    //checks for a message
    if (empty($_POST['postt']) ) {
    $errors[]='You forgot to enter your comments';
    }

    // checks for required file
    // http://amiworks.co.in/talk/handling-file-uploads-in-php/
    if($requirefile=="true") {
    if($_FILES['attachment']['error']==4) {
    $errors[]='You forgot to attach a file';
    }
    }

    //checks attachment file
    // checks that we have a file
    if((!empty($_FILES["attachment"])) && ($_FILES['attachment']['error'] == 0)) {
    // basename — Returns filename component of path
    $filename = basename($_FILES['attachment']['name']);
    $ext = substr($filename, strrpos($filename, '.') + 1);
    $filesize=$_FILES['attachment']['size'];
    $max_bytes=$max_file_size*1024;

    //Check if the file type uploaded is a valid file type.
    if (!in_array($ext, $allowtypes)) {
    $errors[]="Invalid extension for your file: “.$filename.”“;

    // check the size of each file
    } elseif($filesize > $max_bytes) {
    $errors[]= “Your file: “.$filename.” is to big. Max file size is “.$max_file_size.”kb.”;
    }

    } // if !empty FILES

    if (empty($errors)) { //If everything is OK

    // send an email
    // Obtain file upload vars
    $fileatt = $_FILES[‘attachment’][‘tmp_name’];
    $fileatt_type = $_FILES[‘attachment’][‘type’];
    $fileatt_name = $_FILES[‘attachment’][‘name’];

    // Headers
    $headers = “From: $emailfrom”;

    // create a boundary string. It must be unique
    $semi_rand = md5(time());
    $mime_boundary = “==Multipart_Boundary_x{$semi_rand}x”;

    // Add the headers for a file attachment
    $headers .= “\nMIME-Version: 1.0\n” .
    “Content-Type: multipart/mixed;\n” .
    ” boundary=\”{$mime_boundary}\””;

    // Add a multipart boundary above the plain message
    $message =”This is a multi-part message in MIME format.\n\n”;
    $message.=”–{$mime_boundary}\n”;
    $message.=”Content-Type: text/plain; charset=\”iso-8859-1\”\n”;
    $message.=”Content-Transfer-Encoding: 7bit\n\n”;
    $message.=”From: “.$namefrom.”\n”;
    $message.=”Email: “.$emailfrom.”\n”;
    $message.=”Affiliations: “.$affilations.”\n”;
    $message.=”Post: “.$postt.”\n\n”;

    if (is_uploaded_file($fileatt)) {
    // Read the file to be attached (‘rb’ = read binary)
    $file = fopen($fileatt,’rb’);
    $data = fread($file,filesize($fileatt));
    fclose($file);

    // Base64 encode the file data
    $data = chunk_split(base64_encode($data));

    // Add file attachment to the message
    $message .= “–{$mime_boundary}\n” .
    “Content-Type: {$fileatt_type};\n” .
    ” name=\”{$fileatt_name}\”\n” .
    //”Content-Disposition: attachment;\n” .
    //” filename=\”{$fileatt_name}\”\n” .
    “Content-Transfer-Encoding: base64\n\n” .
    $data . “\n\n” .
    “–{$mime_boundary}–\n”;
    }

    // Send the completed message

    $envs = array(“HTTP_USER_AGENT”, “REMOTE_ADDR”, “REMOTE_HOST”);
    foreach ($envs as $env)
    $message .= “$env: $_SERVER[$env]\n”;

    if(!mail($to,$subject,$message,$headers)) {
    exit(“Mail could not be sent. Sorry! An error has occurred, please report this to the website administrator.\n”);
    } else {
    echo ‘Thank You!’. $thanksmessage .”;
    unset($_SESSION[‘myForm’]);
    print_form();

    } // end of if !mail

    } else { //report the errors
    echo ‘Error!The following error(s) has occurred:’;
    foreach ($errors as $msg) { //prints each error
    echo ” – $msg\n”;
    } // end of foreach
    echo ‘Please try again’;
    print_form();
    } //end of if(empty($errors))

    } // end of process_form()
    ?>

  30. piyush jain says:

    i’m using same script to send mail with attachment… but i’m not getting any mail and attachment in inbox and spam also..
    but when i sent this mail, i got the message that attachment has sent successfully..
    please help me in this issue..
    i’m not getting the problem..

  31. Raksha says:

    Hi,
    I tried using your code with attachment but it says mail delivered but I am not getting receiving any mail

    Full Name

     

    Contact No.

     

    Email

     

    Current Technology

     

    Current Location

     

    Who are you ?

    ——— Choose Cource —–
    Freasher
    Experience
    Other

     

    Message

     

    Attachment

    Enter the contents of image:

          
    <?php
    if(isset($_POST['submit']))
    {
    if ($_POST["captcha"] != $_SESSION["cap_code"] OR $_SESSION["cap_code"]=='')
    {
    echo 'Human verification Wrong! ‘;
    }

    $name = $_POST[‘name’];
    $email = $_POST[’email’];
    $phone = $_POST[‘phone’];
    $mess = $_POST[‘message’];
    $tech = $_POST[‘tech’];
    $location = $_POST[‘location’];
    $sub=$_POST[‘subject’];
    $to = ‘rakshafirst@gmail.com’;
    $subject = “Learn Well”;
    $message = “—– You have got message from——————–\n”.
    “$sName\n”.
    “Name: $name\n”.
    “Email : $email\n”.
    “Phone : $phone\n”.
    “Technology:$tech\n”.
    “Location:$location\n”.
    “Subject:$sub\n”.
    “Message : $mess\n”;

    $upload_name=$_FILES[“upload”][“name”];
    $upload_type=$_FILES[“upload”][“type”];
    $upload_size=$_FILES[“upload”][“size”];
    $upload_temp=$_FILES[“upload”][“tmp_name”];
    $fp = fopen($upload_temp, “rb”);
    $file = fread($fp, $upload_size);

    $file = chunk_split(base64_encode($file));
    $num = md5(time());

    //Normal headers

    $headers = “From: Info Mail\r\n”;
    $headers .= “MIME-Version: 1.0\r\n”;
    $headers .= “Content-Type: multipart/mixed; “;
    $headers .= “boundary=”.$num.”\r\n”;
    $headers .= “–$num\r\n”;

    // This two steps to help avoid spam

    $headers .= “Message-ID: \r\n”;
    $headers .= “X-Mailer: PHP v”.phpversion().”\r\n”;

    // With message

    $headers .= “Content-Type: text/html; charset=iso-8859-1\r\n”;
    $headers .= “Content-Transfer-Encoding: 8bit\r\n”;
    $headers .= “”.$message.”\n”;
    $headers .= “–“.$num.”\n”;

    // Attachment headers

    $headers .= “Content-Type:”.$upload_type.” “;
    $headers .= “name=\””.$upload_name.”\”r\n”;
    $headers .= “Content-Transfer-Encoding: base64\r\n”;
    $headers .= “Content-Disposition: attachment; “;
    $headers .= “filename=\””.$upload_name.”\”\r\n\n”;
    $headers .= “”.$file.”\r\n”;
    //$headers .= “–“.$num.”–“;
    $headers .= “–”.$num.”\n”;
    // SEND MAIL
    @mail($to, $subject, $message, $headers);
    fclose($fp);

    //mail($sSendTo, “You have got message from $name”, $sBuffer,$strHeader, “From: $name\r\nReply-To: $email\r\n”);
    //echo ‘alert(“Message Sent Successfully!”);’;
    //header(‘Location:contact.php’);
    }
    ?>

     

    <!–
     

    –>

  32. Thinesh says:

    When i download image by this script from gmail i can’t view the image

  33. Prafulla says:

    Hi,
    this script is working for attachment but it fail to send message(body of mail)…it show blank message

  34. I have a problem when attaching a docx file.
    It sent successfully but cant open in mail box.

    it works fine with doc file.

    here is the my code

    $strTo = $_POST[“txtTo”];
    $strSubject = $_POST[“txtSubject”];
    $strMessage = nl2br($_POST[“txtDescription”]);

    //*** Uniqid Session ***//
    $strSid = md5(uniqid(time()));
    $strHeader = “”;
    $strHeader .= “MIME-Version: 1.0\n”;
    $strHeader .= “Content-Type: multipart/mixed; boundary=\””.$strSid.”\”\n\n”;
    $strHeader .= “This is a multi-part message in MIME format.\n”;
    $strHeader .= “–“.$strSid.”\n”;
    $strHeader .= “Content-type: text/html; charset=utf-8\n”;
    $strHeader .= “Content-Transfer-Encoding: 7bit\n\n”;
    $strHeader .= $strMessage.”\n\n”;
    //*** Attachment ***//
    if($_FILES[“fileAttach”][“name”] != “”)
    {
    $strFilesName = $_FILES[“fileAttach”][“name”];
    $strContent = chunk_split(base64_encode(file_get_contents($_FILES[“fileAttach”][“tmp_name”])));
    $strHeader .= “–“.$strSid.”\n”;
    $strHeader .= “Content-Type: application/octet-stream; name=\””.$strFilesName.”\”\n”;
    $strHeader .= “Content-Transfer-Encoding: base64\n”;
    $strHeader .= “Content-Disposition: attachment; filename=\””.$strFilesName.”\”\n\n”;
    $strHeader .= $strContent.”\n\n”;
    }

    $flgSend = @mail($strTo,$strSubject,$strMessage,$strHeader);

  35. Chintan says:

    Thanks for sharing. 🙂
    Your Code is working good with gmail account.
    but when i trying to send mail on yahoo. it’s give me error on attachment area.

  36. Durga Prasanna Acharya says:

    Thanks a lot.. sir.

    nice post..nice code..
    but one question it goes to spam..right. so how it would go to inbox….
    please suggest me…

    thanks in Advance…

    1. Vivek Moyal says:

      Sir it depends on only over your IP and other header settings.

  37. Rakesh Mishra says:

    Hi, vivek
    Thank you for sharing this information. But Its not working when ever i have tried from demo too. Please check your code.

    1. Vivek Moyal says:

      If you are using windows that it might work but in Linux it works as you can check the comments

  38. monica says:

    Thank you so so much….
    great job

  39. Nishu says:

    I used your email sending code with Attachment, Email sent successfully but my full message is not displayed. Please help me as soon as possible

  40. Kiran says:

    Hi Vivek,

    Great Information you have shared and thanks for that.
    Actually I am facing a problem like i am not able to send a mail with attachment with your code. When i removed headers in mail() or removed the attachment header code then it is going mail without attachment.

    So i think there is a problem in your headers attachment code.

    http://tenjerla.com/DEV/upload.php

    <?php

    if(isset ($_POST["send"]))
    {
    $upload_name=$_FILES["upload"]["name"];
    $upload_type=$_FILES["upload"]["type"];
    $upload_size=$_FILES["upload"]["size"];
    $upload_temp=$_FILES["upload"]["tmp_name"];
    $message=$_POST["msg"];
    $subject = $_POST["subject"];
    $to=$_POST["to"];

    if($message==""||$subject==""||$to=="")
    {
    echo 'Please fill all fields’;
    }
    else
    {
    $fp = fopen($upload_temp, “rb”);
    $file = fread($fp, $upload_size);

    $file = chunk_split(base64_encode($file));
    $num = md5(time());

    //Normal headers

    $headers = “From: Info Mail\r\n”;
    $headers .= “MIME-Version: 1.0\r\n”;
    $headers .= “Content-Type: multipart/mixed; “;
    $headers .= “boundary=”.$num.”\r\n”;
    $headers .= “–$num\r\n”;

    // This two steps to help avoid spam

    $headers .= “Message-ID: \r\n”;
    $headers .= “X-Mailer: PHP v”.phpversion().”\r\n”;

    // With message

    $headers .= “Content-Type: text/html; charset=iso-8859-1\r\n”;
    $headers .= “Content-Transfer-Encoding: 8bit\r\n”;
    $headers .= “”.$message.”\n”;
    $headers .= “–“.$num.”\n”;

    // Attachment headers

    $headers .= “Content-Type:”.$upload_type.” “;
    $headers .= “name=\””.$upload_name.”\”r\n”;
    $headers .= “Content-Transfer-Encoding: base64\r\n”;
    $headers .= “Content-Disposition: attachment; “;
    $headers .= “filename=\””.$upload_name.”\”\r\n\n”;
    $headers .= “”.$file.”\r\n”;
    $headers .= “–“.$num.”–“;

    // SEND MAIL

    @mail($to, $subject, $message, $headers);

    fclose($fp);

    echo ‘Mail sent please check inbox and spam both ‘;
    }
    }

    ?>

    To:

    Subject:

    Message:

    Attachment*:

    1. Vivek Moyal says:

      Thank You …. noooo its not like that its just depends on the hosting. But leave it atlast you got what you want so just enjoy. I will see and try to modify it more.

  41. Narasimha P says:

    Hi Bro,

    How can we send mail with attachment using perl configuration in PHP ?

  42. Santosh Kumar says:

    Hello Vivek, your mail application is awesome. It’s really work……

    I have query, Do you have any idea about instance mail send to buyers when he/she buy the product from any online shopping site? Because I tried but still didn’t get any solution.

  43. Kumar says:

    Hi Vivek,

    Thanks for ur posting. It is working well and I can upload text file only. But I can not upload doc,xls, zip, image files. Can you give any idea to upload these files.

    Thanks and Regards,
    Kumar

    1. Vivek Moyal says:

      See comments above there you will get the solution for it

  44. Vipin Soni says:

    Dear Vivek sir,

    Thanks for this code. i was making efforts to send mail for last one week and i got solution after the use of this code. thanks again. 🙂

  45. S.R.Rama Krishna says:

    Thank you very useful code

  46. kunal kotkar says:

    Hi sir, jai mata di
    pls snd me the file for windows server email wit attachment on the below email id
    kunalkotkars@gmail.com
    pls help us i m desperately waiting for u r rply
    gud day
    hav a nic day

  47. Dhaval says:

    Hi Vivek,

    Please suggest me something for sending mail from windows server as your code is not working on same.

    Please replay ASAP as its very urgent..

    Thanx in Advance..!!

    1. Vivek Moyal says:

      Sorry for this because it i work only for Linux server

      1. Dhaval says:

        I got solution for windows mail with attachment..

        ReferFor Send email with attachment on window server and unix server

        http://www.vasplus.info/tutorial.php?id=96&topic=Send%20Email%20with%20Cc,%20Bcc%20and%20File%20Attachment%20using%20Ajax,%20Jquery%20and%20PHP%20-%20Updated#.Ud0qTfn0y69

  48. usha says:

    Hi sir,
    I need a php code to send email to client and get email address from mysql table and with docx attachment the same may be sent to client.we are using roundcube.kindly provide the code.
    Thanks

    1. Vivek Moyal says:

      Use our code its already in working condition and if you need your mail id form mysql than put your logic for it. If you have any issue with your code than tell us about the problem we will help you. We are here to help you not for your working

  49. ajay says:

    can i make two brows box?
    how to make variable for two attachment file

    1. Vivek Moyal says:

      Yes you can but you have to make array of browse than have to get that attachment

      1. ajay says:

        Thanks

  50. Jay says:

    Hi dude, thans for this, mine doesnt give me any errors, it just doesnt send any thing, is there anyway you can help me please? im on a linux live VPS.

    1. Vivek Moyal says:

      Have you checked spam or not ….. and is my demo working at your side

      1. Jay says:

        Yes i did, i have other mail funcion working on other page but this one doesn’t.

        I dont give any errors at all, thats what it getting to me!

        1. Vivek Moyal says:

          If there is no any error than on which part we should work we also dont know. If there will be any error than we will sort that out but if we dont know anything than how. Try to send it without the attachment and without the attachment header

  51. Akhmad says:

    Hi Vivek, Thanks a lot mate, That code helped me a lot. What I am looking for it exactly this 😉

  52. Rizwan says:

    html body with attachment is not working

  53. Sowndar says:

    Hi….
    first of all thanks for the tutorial….
    Your demo (provided in this page) works fine….
    Am able to get email in yahoo and outlook…
    But when i use your demo in my website (which is hosted and not runned in localhost) it is not working…
    I am getting the message “Mail sent please check inbox and spam both ” but i did’nt recieve any mail… both in yahoo and outlook….
    please help….!
    url : http://www.researchintern.net/emailAttachment.php (just to check whether it is working or not, i’ve included it there…..)

    1. Vivek Moyal says:

      Your demo is working i have used your link and its working. Please check again

      1. Sowndar says:

        Which account did you use to check?
        i mean is it gmail or yahoo or outlook?

  54. urmila says:

    thanks

    i am trying this code, word file sent to gmail but not to yahoo, and i am not able to send image even to gmail…

    whats the problem, i used your demo code as it is

    1. Vivek Moyal says:

      For image file please check is image allowed in the script or not. For not getting on yahoo thats the matter of thinking. Have you checked the spam folder

  55. Besol says:

    Hi Vivek,

    I used Your script, its work fine, but its not sending the message. Even your Demo here doesnt’s sent me the value I put to the box named Message. Can you help m work this out?

    thx in advance,

    1. Vivek Moyal says:

      Check your spam folder because You are the first person who is saying that my demo is not working !!!!!! 🙂

      1. Besol says:

        Hey again,
        sorry for late response, vacations ;p but problem stands still :). Anyway, I mean that the mail is sending ok, my box is always receiving it, but always without VALUE of field named Message. Atachment is ok, but there is no any text. empty mail with only atachment.

  56. Ahmad says:

    Nice tutorials very helpful.

  57. Thanks a bunch, Vivek!
    *Cheers*

    1. Hey again,
      I noticed that the message is empty in mail. I verified that I have content in message before calling @mail function. What could be wrong?

      1. Vivek Moyal says:

        First of all check these two steps.

        1. Should be an online application not over the localhost
        2. Should be on Linux server only not on windows

        1. Yeah both are correct. If i simply enter “$message = ‘Hello’;” . it works. but,
          $message = “”;
          $job = (isset($_POST[‘job’])?$_POST[‘job’]:”N/A”);
          $name = (isset($_POST[‘name’])?$_POST[‘name’]:”N/A”);
          $message .= “Applied for: $job”;
          $message .= “\nName: $name”;

          just sends out empty message (although, the attached file still appears in Email).
          Also, tried with simple:
          $message .= “Name: ” . $_POST[‘name’];
          $message .= “Job: ” . $_POST[‘job’];

          Same empty message (but attached file exists)

          1. Vivek Moyal says:

            Have you checked that your form is sending the values and its method is post. Please recheck the fields name. Your problem is getting null value try to check that you are getting the values or not

            1. Hi Vivek,
              I figured It’s related to passing the data of a “hidden” input. The $_POST[‘job’] comes from a hidden input. Only this causes the message to go full empty.
              This is how I have declared it:

              Another thing, using “\n” doesn’t seem to break the line, and using “” again sends message full empty..

              1. Another thing, If I echo $_POST[‘job’]. It is displayed normally.

              2. I meant using “\n” and using ” ” *

                1. Grr.. i mean using HTML break tag.
                  Wordpress is eating it up.

                  1. Vivek Moyal says:

                    I am not getting what you want to say because you have posted 4 comments and what i understandis You have done with your problem and its working fine as you said

                    1. Okay.
                      The problem is when I concatenate value of a hidden field to $message.
                      Then, the message goes empty.
                      I echo’d the value of the hidden field and it gets echo’d fine.

                    2. Vivek Moyal says:

                      Show me the code of field and getting the value of the field

                    3. Vivek Moyal says:

                      Pastebin is blocked in India. try something else

                    4. That’s weird, I’m in India too..

                      http://jsfiddle.net/TGhXU/

                    5. Hi Vivek,
                      Thanks for helping..

                      Here’s how the $_POST[‘job’] is “echo”d.

                      With so many weird blank spaces that even, the trim() function doesn’t remove them.
                      While the values of other fields are being echo’d normally.

                      http://imageshack.us/f/805/problembf.jpg/

                    6. Vivek Moyal says:

                      try this one
                      http://vivekmoyal.in/testing/test.php

                      Your code is working fine

                    7. Vivek Moyal says:

                      Thank You Thank You Thank You Thank You Thank You Thank You Thank You Thank You Thank You …… I was trying for it now i got it Thank You

                  2. By looking at the source, I noticed some whitespace in value=”” tag before “TeleCallers” text.

                    <input type="hidden" name="job" value="<>TeleCallers” id=”job” />

                    Did you intentionally add that whitespace?

                    1. Vivek Moyal says:

                      Yes i have added the whitespace as you said your trim is not trimming so i have tested it with that one. Thats great that you have done that

                      Can you help me out ………. How to find the city name through the help of IP. I need it for my weather widget

                  3. I found the solution:
                    It is to remove ANY white-space (including indents) before and after the hidden field.

                    Demonstration:
                    http://jsfiddle.net/UHPEc/1/

                    Thanks a lot for helping, Vivek!

                  4. Thanks to you too! 🙂

  58. syed furqhan says:

    hey there vivek,
    i’m implementing this in my project, but it is on localhost , lampp with linux can u help me out with this and setting up in localhost?

    1. Vivek Moyal says:

      As i already said it will not work over localhost

  59. Divyang says:

    Sir,
    i need php script that send email to me and also send thank you email to who fill up the contact form..

    1. Vivek Moyal says:

      You can use the mail function and get the mail id from filled form and use the mail() function to send the mail to the person who filled the form

  60. ankit says:

    i tried your code, the attachment is working but my attached file is going to blank. nothing display in attach file

    1. Vivek Moyal says:

      See while the attachment is attached check that code is having the full name of the file with the extension if not than it will show this problem to you

  61. Phantomeme says:

    hi, i have a little problem : when i try to submit it on my website, it says :

    Warning: fopen() [function.fopen]: Filename cannot be empty in /homez.727/sltransl/www/script/sendmail.php on line 39

    Warning: fread() expects parameter 1 to be resource, boolean given in /homez.727/sltransl/www/script/sendmail.php on line 40

    Warning: fclose() expects parameter 1 to be resource, boolean given in /homez.727/sltransl/www/script/sendmail.php on line 93

    i just wrote the same code as yours

    1. Vivek Moyal says:

      Check your form and the upload field ID and name. This is due to the null value which means the upload field is missing or its value is missing.

  62. pratama says:

    nice tutotial.. thanks
    this is very help

  63. Bijoy says:

    hey Vivek

    I have written this code after researching ur and some other codes and tutorials online to upload a file (CV in this case) and send it to multiple persons ( me and the user or uploader) now there seems to be a problem, I get the complete email with all the details but no uploaded file and I cannot figure out whats wrong can you please help

    Thanks in advance

    <?php
    $errors = '';
    $myemail = 'info@domain.in';//<—–Put Your email address here.
    $noreplyemail = 'careers-no-reply@domain.in';//<—— No reply email
    if(empty($_POST['first_name']) ||
    empty($_POST['last_name']) ||
    empty($_POST['position']) ||
    empty($_POST['tele-phone']) ||
    empty($_POST['e-mail']) ||
    empty($_POST['contact-me-by']) ||
    empty($_POST['cover-letter']))
    {
    $errors .= "\n Error: all fields are required";
    }

    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $position = $_POST['position'];
    $phone = $_POST['tele-phone'];
    $email = $_POST['e-mail'];
    $upload_name=$_FILES["upload"]["name"];
    $upload_type=$_FILES["upload"]["type"];
    $upload_size=$_FILES["upload"]["size"];
    $upload_temp=$_FILES["upload"]["tmp_name"];
    $contact-me-by = $_POST['contact-me-by'];
    $cover-letter = $_POST['cover-letter'];

    if (!preg_match(
    "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
    $email))
    {
    $errors .= "\n Error: Invalid email address";
    }

    if( empty($errors))
    {
    $to1 = $myemail;
    $to2 = $email;

    $email_subject1 = "Application for $position from $first_name";
    $email_subject2 = "We have recieved your Application for the position of $position";

    $email_body1 = "Dear Sir \n \n"
    "You have received an Application for the position of $position.\n ".
    " Here are the details of the Applicant:\n \n First Name: $first_name \n Last Name: $last_name \n Position: $position \n Telephone: $phone \n Email: $email \n Contact me by: $contact-me-by \n Covet Letter: $cover-letter \n \nThank You \n \nMy Companys \nwww.domain.in";
    $email_body2 = "Dear $first_name \n \n".
    "Thank you for Applying to My Companys, We have recieved your Application for the position of $position and we will get in touch with you as soon as possible. \n ".
    "The Please Check the details provided by you:\n \n First Name: $first_name \n Last Name: $last_name \n Position: $position \n Telephone: $phone \n Email: $email \n Contact me by: $contact-me-by \n Covet Letter: $cover-letter \n \nThank You \n \nMy Companys \nwww.domain.in \n \n \n";
    "Disclaimer: This email and any files transmitted with it are intended solely for the use of the addressee(s) only and may contain confidential and/or privileged information. If you are not the addressee, then this message is not intended for you and be advised that you have received this email in error, please notify the sender and delete this email and attachments, if any, from your system immediately. Receipt of this email by you shall not give rise to any liability on the part of My Companys. For more information about My Company, visit us at http://www.domain.in \n \n"
    "Virus Warning: Although the company has taken reasonable precautions to ensure that no viruses are present in this email, the company cannot accept responsibility for any loss or damage arising from the use of this email or attachment.";

    $fp = fopen($upload_temp, "rb");
    $file = fread($fp, $upload_size);

    $file = chunk_split(base64_encode($file));
    $num = md5(time());

    $headers1 = "From: $noreplyemail \n";
    $headers1 .= "Reply-To: $email";
    $headers1 .= "MIME-Version: 1.0\r\n";
    $headers1 .= "Content-Type: multipart/mixed; ";
    $headers1 .= "boundary=".$num."\r\n";
    $headers1 .= "–$num\r\n";

    // This two steps to help avoid spam

    $headers1 .= "Message-ID: \r\n”;
    $headers1 .= “X-Mailer: PHP v”.phpversion().”\r\n”;

    // With message

    $headers1 .= “Content-Type: text/html; charset=iso-8859-1\r\n”;
    $headers1 .= “Content-Transfer-Encoding: 8bit\r\n”;
    $headers1 .= “”.$email_subject1.”\n”;
    $headers1 .= “–“.$num.”\n”;

    // Attachment headers

    $headers1 .= “Content-Type:”.$upload_type.” “;
    $headers1 .= “name=\””.$upload_name.”\”r\n”;
    $headers1 .= “Content-Transfer-Encoding: base64\r\n”;
    $headers1 .= “Content-Disposition: attachment; “;
    $headers1 .= “filename=\””.$upload_name.”\”\r\n\n”;
    $headers1 .= “”.$file.”\r\n”;
    $headers1 .= “–“.$num.”–“;

    $headers2 = “From: $noreplyemail \n”;
    $headers2 .= “Reply-To: $myemail”;
    $headers2 .= “MIME-Version: 1.0\r\n”;
    $headers2 .= “Content-Type: multipart/mixed; “;
    $headers2 .= “boundary=”.$num.”\r\n”;
    $headers2 .= “–$num\r\n”;

    // This two steps to help avoid spam

    $headers2 .= “Message-ID: \r\n”;
    $headers2 .= “X-Mailer: PHP v”.phpversion().”\r\n”;

    // With message

    $headers2 .= “Content-Type: text/html; charset=iso-8859-1\r\n”;
    $headers2 .= “Content-Transfer-Encoding: 8bit\r\n”;
    $headers2 .= “”.$email_subject2.”\n”;
    $headers2 .= “–“.$num.”\n”;

    // Attachment headers

    $headers2 .= “Content-Type:”.$upload_type.” “;
    $headers2 .= “name=\””.$upload_name.”\”r\n”;
    $headers2 .= “Content-Transfer-Encoding: base64\r\n”;
    $headers2 .= “Content-Disposition: attachment; “;
    $headers2 .= “filename=\””.$upload_name.”\”\r\n\n”;
    $headers2 .= “”.$file.”\r\n”;
    $headers2 .= “–“.$num.”–“;

    mail($to1,$email_subject1,$email_body1,$headers1);
    fclose($fp);
    mail($to1,$email_subject2,$email_body2,$headers2);
    fclose($fp);

    //redirect to the ‘thank you’ page
    header(‘Location: http://www.domain.in/‘);
    }
    ?>

    Contact form Error

    1. Vivek Moyal says:

      This error out of my hands……. because this code works well at my end so i cant check it why it is not working on many hosting servers. First check that you have a Linux based server it will not work over the windows.

      1. bijo says:

        Yeh it works fine now … figured it out … stupidity on my Side but do u have any idea on how to restrict the attachments to int PDFs n docx or doc

        Thnx

        1. Vivek Moyal says:

          Use this it will solve your problem

          $strresume_name=$_FILES[“strresume”][“name”];
          $strresume_type=$_FILES[“strresume”][“type”];
          $strresume_size=$_FILES[“strresume”][“size”];
          $strresume_temp=$_FILES[“strresume”][“tmp_name”];
          if($_FILES[“strresume”][“type”]==”application/pdf”||$_FILES[“strresume”][“type”]==”application/msword”||$_FILES[“strresume”][“type”]==”application/vnd.openxmlformats-officedocument.wordprocessingml.document”)

  64. Phantomeme says:

    fortunately there are guys like you vivek… what would i do without you?

    1. Vivek Moyal says:

      Thank you….. 🙂 … Just keep smiling

  65. vikas says:

    wow..nice work sir.

  66. Ankita says:

    I vivek, Is there any way to save draft in email editor?

    1. Vivek Moyal says:

      Hein !!!!!……… What ? 😎

  67. shiva says:

    hi brother
    i see u r code but i want to attached so many files give a size limit how it we will do……

  68. Sara says:

    If you want you can check it on live link with code: http://klshospital.co.in/careers.html

    I am not receiving emails

  69. Sara says:

    Sir,
    We have texting on linux and actual sever only.. Its shows “Mail sent please check inbox and spam both ” But in real Mail is nt reeving(not even spam)…
    plz help …

    1. Vivek Moyal says:

      My demo link is working at your end or not. If now than send me your downloaded file i will put that file on my server than will test it. Please change the name of the file so that we will check it our

      1. Sara says:

        No… Its not working. I uploaded same code which you provided as on my sever.. After submission of that form, Its only shows “Mail sent please check inbox and spam both ” But actually its not receiving any EMail.. 🙁

        1. Vivek Moyal says:

          Please send me the careers.html file and the php code which you are using in your project. Mail me at vivek@simplyitsols.com. I will upload it over my server and than i will try it

  70. Sara says:

    Hi, I have used same code you provided on sever.. I dint got any Email (nt in spam) Send m working form…

    1. Vivek Moyal says:

      Let me check it out again because my demo link is working and your downloaded file is not working whereas both the files are same. Not even a single character difference………. 🙁

      1. Divyang says:

        Sir it is not possible that same code is working in demo link and your downloaded code is not working…

        there is something sir, that you dont wont to share with us…

        1. Vivek Moyal says:

          Hhahaha….. Nothing is secret bro why should i do this. We work to help others and i have checked it and i told my friends to check it everyone is saying that its working please check ….. that your server is linux based it will not work over windows. If you are testing it than the page should be on server not over your pc.

          1. Divyang says:

            sir,
            i uploaded all my files in windows hosting…
            does your code work in windows hosting??

            1. Vivek Moyal says:

              Nop it will not work on windows hosting

              1. Divyang says:

                Sir,
                i change my hosting to linux…
                and upload all files in linux hosting..
                and i upload your file also but same problem…

                1. Vivek Moyal says:

                  I am working on another script as it is creating problems. New one will not let you face these problems.

                  1. Divyang says:

                    thank you very much sir,
                    please send me working scripts for send file attachment…

                    i am waiting for your response…

                    1. Divyang says:

                      Sir,
                      how to send auto reply email to sender??

                      Please guide me.

                    2. Vivek Moyal says:

                      You can do it through your email service provider. If you are gmail user you can go to settings and you will find the solutions of your problem.

  71. Divyang says:

    Only Demo link Is working….
    given code is not working….

    1. Vivek Moyal says:

      I have uploaded the file again please check this time its the same one which we are using for demo link.

      1. Divyang says:

        thank you for reply
        but
        Same problem Sir Only Message change…..

        1. Vivek Moyal says:

          If you are using it over the localhost than it will not work your work should be online

          1. Divyang says:

            thank you once again,
            i m uploading that script to my domain and i dont change anything in your script but it only display message that “Mail sent please check inbox and spam both” but message did not come to email…

            1. Vivek Moyal says:

              Give me the link where you are using it

                1. Vivek Moyal says:

                  Check your mail i have sent you the exact file which i am using at my demo check spam also

                  1. Divyang Jariwala says:

                    i upload that file you send….

                    link is : http://www.stallionflags.com/emailAttachment.php

                    same problem, check yourself by open this link…

                    and i check both inbox and spam box also.

                  2. priyanka says:

                    hi i m final year stundent i tried ur code in my project but in demo its working but wen the same code its not working

                    1. anoop says:

                      hello dear i am having the same problem. if you got the solution of this thn please also give response.

  72. Vikam says:

    bro your artical is nise now i have a query that how can i putup validation for in this code
    that only zip file will upload and show error when upload other file

    1. Vivek Moyal says:

      try to check $upload_type=$_FILES[“upload”][“type”];

      It will help you to put the validation

  73. D says:

    Hi Vivek

    Ive tried your code and it doesnt seem to be looking for me. Ive uploaded it to my test website and Im getting nothing from it. I have changed 2 things in the code

    $headers = “From: Info Mail\r\n”;

    and

    if($message==””||$subject==””||$to==”myemiladdress”)

    I have altered the permissions on the file.

    Any help would be gratefull
    🙂

    1. D says:

      messed that up alittle

      Hi Vivek

      Ive tried your code and it doesnt seem to be working for me. Ive uploaded it to my test website and Im getting nothing from it. I have changed 2 things in the code

      $headers = “From: Info Mail\r\n”;

      and

      if($message==””||$subject==””||$to==”myemiladdress”)

      I have altered the permissions on the file.

  74. hari.S.babu says:

    The maqil is going to spam.

    1. Vivek Moyal says:

      It depends over the mail provider

  75. Fujale says:

    Hello.can u found any solution for my problem

    1. Vivek Moyal says:

      I told you earlier that send me your file i will test it at my end. And if i found any problem than i will revert you

  76. fujale says:

    Those are session values no problem with that values…i checked by printing..check this link http://www.dudekula.com/newdudekula/ex.php
    This is an example

    1. Vivek Moyal says:

      Here i can check your html only …. so i need your HTML and PHP both send me this page as mail i will check it and revert you again in couple of minuets

  77. fujale says:

    what could be the problem…I am trying from couple of days

    1. Vivek Moyal says:

      Bro i think you are having some code problem….. I not getting where you are getting the values for $to=$refid; $from=$email; these 2 variables ……. i saw your code but i dont know where is your $refid and $email

    2. Vivek Moyal says:

      If you still got the error than mail me your html and php code for this link i will see and send it back to you….

    1. Nice post vivek. I am trying it now if any issues i will comment..

  78. fujale says:

    I checked on hosting server to…But it reflecting same error

    1. Vivek Moyal says:

      show me the link where you are using it

  79. fujale says:

    no yaar…demo is working perfectly…

    1. Vivek Moyal says:

      I think you are working over the localhost. Use your code over the hosting it will work as i have checked it again it shows the success message if i use it on localhost but didnt send the message. and if i am using the same code over my server it works fine without any issues

  80. fujale says:

    Error in the sense…mail is not sending…

    1. Vivek Moyal says:

      Please send the whole HTML

  81. fujale says:

    PHP CODE

    if(isset($_POST[‘submit’]) && $_POST[‘submit’]==”Post”)
    {
    $upload_name=$_FILES[“upload”][“name”];
    $upload_type=$_FILES[“upload”][“type”];
    $upload_size=$_FILES[“upload”][“size”];
    $upload_temp=$_FILES[“upload”][“tmp_name”];
    $message=”Thanks for Refereing”;
    $subject = “Forwarding Resume”;
    $to=$refid;
    $from=$email;
    //echo $upload_name;
    //echo $upload_type;
    //echo $upload_size;
    //echo $upload_temp;

    $fp = fopen($upload_temp, “rb”);
    $file = fread($fp, $upload_size);
    $file = chunk_split(base64_encode($file));
    $num = md5(time());

    //Normal headers

    $headers = “From:”.$from.”\r\n”;
    $headers .= “MIME-Version: 1.0\r\n”;
    $headers .= “Content-Type: multipart/mixed; “;
    $headers .= “boundary=”.$num.”\r\n”;
    $headers .= “–$num\r\n”;

    // This two steps to help avoid spam

    $headers .= “Message-ID: \r\n”;
    $headers .= “X-Mailer: PHP v”.phpversion().”\r\n”;

    // With message

    $headers .= “Content-Type: text/html; charset=iso-8859-1\r\n”;
    $headers .= “Content-Transfer-Encoding: 8bit\r\n”;
    $headers .= “”.$message.”\n”;
    $headers .= “–“.$num.”\n”;

    // Attachment headers

    $headers .= “Content-Type:”.$upload_type.” “;
    $headers .= “name=\””.$upload_name.”\”r\n”;
    $headers .= “Content-Transfer-Encoding: base64\r\n”;
    $headers .= “Content-Disposition: attachment; “;
    $headers .= “filename=\””.$upload_name.”\”\r\n\n”;
    $headers .= “”.$file.”\r\n”;
    $headers .= “–“.$num.”–“;

    // SEND MAIL

    $mail = @mail($to, $subject, $message, $headers);
    fclose($fp);
    $mail ? $msg = “Thanku!!!”: $msg =”Sorry!!!”;
    }

  82. fujale says:

    My html Code

    Apply Job

    <form class="form-horizontal" name="artfrm" enctype="multipart/form-data" action="” method=”post” onSubmit=”return valid();”>

    Name

    <input type="text" name="txtname" id="txtcmpname" value="”>

    Email

    <input type="text" name="txtemail" id="txtemail" value= >

    Resume


    1. Vivek Moyal says:

      Wait a moment i will send you the working code if you are getting some error with the working demo

  83. fujale says:

    I am using similar code like u, but failed to send attachment…Now i used your code same result yaar…attachments are sending.it returns false always…could you please help me..thank u

    1. Vivek Moyal says:

      What error it is showing can you send me the email photo to my mail id ……. vivek@simplyitsols.com

  84. harsha says:

    one more thing I want to ask you that…………..could u plz suggest me how to fetch/retrieve values from mysql database to front side ….i can fetch such from backend too frontend in table………….But I don’t know how to disply it in particula HTML div’s…???Plz anybody suggest me if u know how to code for this…???

  85. harsha says:

    thnk for this code VIvek…………………..But I’ve one query that i’ve written code for sending email with attachments using php………..it shows me the ” successfuly send ur mail attachment” message …..I’ve got mail in my Junk folder and all information which I’ve send from form I’ve got in mail format(Message body) instead of Image which I’ve attached using filetype…………..Instead of showing image it shows me only emplty default box……………How can I get that image attachment also to mail……………plz do suggest………thanking u….

    1. Vivek Moyal says:

      For spam i cant say anything because it is based on or provider. And i think code is working fine i am using this same code over a website and i am getting resumes always as attachment

  86. Motyar says:

    Very useful Vivek.
    -Motyar

    1. Vivek says:

      Thank You

    2. Mahendra Mahajan says:

      thanks sir i am use this code for sending mail with attachment but when i am adding another field in this form they can’t send in mail what i do for this problem,please tell me .

      1. shahid says:

        same method but use dont use
        $headers .= “–“.$num.”–“;
        because after this execution stop use
        $headers .= “–“.$num.”\n”;
        until last $headers .=”” call

Leave a comment

Your email address will not be published. Required fields are marked *