Posted in: PHP, Tech-Byte, Tips

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

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.

EAttachment
EAttachment
emailAttachment.rar
1.1 KiB
3962 Downloads
Details...

Comments (192) on "Send Email with Attachment in PHP, Send Attachment in Email in PHP"

  1. 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…

  2. 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

  3. 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.

  4. <?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

  5. 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?

  6. 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. 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.

  7. @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

  8. 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

  9. 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. 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

  10. 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.

  11. 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!

  12. 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+ “)

  13. 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

  14. 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

  15. 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()
    ?>

  16. 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..

  17. 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’);
    }
    ?>

     

    <!–
     

    –>

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

  19. 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);

  20. 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.

  21. 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…

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

  23. 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

  24. 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. 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.

  25. 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.

  26. 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

  27. 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. πŸ™‚

  28. 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

  29. 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..!!

  30. 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. 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

  31. 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. 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. 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

  32. Hi Vivek, Thanks a lot mate, That code helped me a lot. What I am looking for it exactly this πŸ˜‰

  33. 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…..)

  34. 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. 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

  35. 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. 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.

    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. 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. 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. 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. 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. 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

  36. 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?

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

    1. 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

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

    1. 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

  39. 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. 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.

  40. 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. 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. 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. 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”)

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

  42. 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. 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. 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.. πŸ™

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

    1. 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. 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. 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. sir,
            i uploaded all my files in windows hosting…
            does your code work in windows hosting??

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

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

                    i am waiting for your response…

                    1. 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.

          1. 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. hello dear i am having the same problem. if you got the solution of this thn please also give response.

  44. 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

  45. 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. 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.

    1. 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

    1. 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

    1. 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

  46. 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!!!”;
    }

  47. 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


  48. 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

  49. 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…???

  50. 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. 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

    1. 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. same method but use dont use
        $headers .= “–“.$num.”–“;
        because after this execution stop use
        $headers .= “–“.$num.”\n”;
        until last $headers .=”” call

Leave a Reply

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