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.
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.
Thanks Vivek, I was able to sending mail with attachment by using the code.
Demo is not working
I am using windows sir, I am also getting the same problem
I actually have the same problem with the other commenters, I used your code but there was no mail.
Which hosting you are using Linux or Windows
haaii,.. its not working.. i got a success mail message.. bt i could not get any mail.
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…
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
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.
Please check when you submit the script you are getting the text in mail body variable.
help i also didnot get mail
same problems
me… the resume upload successful but its size 0 byte
Which hosting you are using linux or windows
thanks bro…. thank you very much…. your are the best
Hi Vivek Sir,
i
Your The Best Dude..ThankYou
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 .. 🙁
Which hosting platform you are using …. windows or linux
i just download you code file and run .. but i get no mail …..
thank you very much.
Vivek thank you very much… This is an excellent code…
<?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
Which hosting you are using linux or windows
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?
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
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?.
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.
@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
Try to put \n at the end of the message than try. I read somewhere that putting \n will solve this problem
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
For outlook i have never used it. I cant say anything about it….. speechless
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.
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
thanks for reply
but i am using papahosting Linux hosting server.
Than try to contact with your hosting provider may be they are blocking the script
can you say me how to upload multiple attachment and send it using php
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.
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!
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+ “)
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
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
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
Sir i want to use this code but i want to know what i should be name of html and the php hehe 🙂
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()
?>
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..
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’);
}
?>
<!–
–>
When i download image by this script from gmail i can’t view the image
Hi,
this script is working for attachment but it fail to send message(body of mail)…it show blank message
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);
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.
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…
Sir it depends on only over your IP and other header settings.
Hi, vivek
Thank you for sharing this information. But Its not working when ever i have tried from demo too. Please check your code.
If you are using windows that it might work but in Linux it works as you can check the comments
Thank you so so much….
great job
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
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*:
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.
Hi Bro,
How can we send mail with attachment using perl configuration in PHP ?
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.
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
See comments above there you will get the solution for it
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. 🙂
Thank you very useful code
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
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..!!
Sorry for this because it i work only for Linux server
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
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
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
can i make two brows box?
how to make variable for two attachment file
Yes you can but you have to make array of browse than have to get that attachment
Thanks
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.
Have you checked spam or not ….. and is my demo working at your side
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!
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
Hi Vivek, Thanks a lot mate, That code helped me a lot. What I am looking for it exactly this 😉
html body with attachment is not working
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…..)
Your demo is working i have used your link and its working. Please check again
Which account did you use to check?
i mean is it gmail or yahoo or outlook?
It was gmail
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
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
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,
Check your spam folder because You are the first person who is saying that my demo is not working !!!!!! 🙂
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.
Nice tutorials very helpful.
Thanks a bunch, Vivek!
*Cheers*
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?
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
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)
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
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..
Another thing, If I echo $_POST[‘job’]. It is displayed normally.
I meant using “\n” and using ” ” *
Grr.. i mean using HTML break tag.
Wordpress is eating it up.
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
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.
Show me the code of field and getting the value of the field
http://pastebin.com/fwggjWM3
Pastebin is blocked in India. try something else
That’s weird, I’m in India too..
http://jsfiddle.net/TGhXU/
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/
try this one
http://vivekmoyal.in/testing/test.php
Your code is working fine
I’d use an API. Here’s one:
http://www.ipinfodb.com/ip_location_api.php
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
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?
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
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!
Thanks to you too! 🙂
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?
As i already said it will not work over localhost
Sir,
i need php script that send email to me and also send thank you email to who fill up the contact form..
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
i tried your code, the attachment is working but my attached file is going to blank. nothing display in attach file
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
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
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.
nice tutotial.. thanks
this is very help
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
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.
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
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”)
fortunately there are guys like you vivek… what would i do without you?
Thank you….. 🙂 … Just keep smiling
wow..nice work sir.
I vivek, Is there any way to save draft in email editor?
Hein !!!!!……… What ? 😎
hi brother
i see u r code but i want to attached so many files give a size limit how it we will do……
If you want you can check it on live link with code: http://klshospital.co.in/careers.html
I am not receiving emails
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 …
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
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.. 🙁
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
Hi, I have used same code you provided on sever.. I dint got any Email (nt in spam) Send m working form…
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………. 🙁
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…
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.
sir,
i uploaded all my files in windows hosting…
does your code work in windows hosting??
Nop it will not work on windows hosting
Sir,
i change my hosting to linux…
and upload all files in linux hosting..
and i upload your file also but same problem…
I am working on another script as it is creating problems. New one will not let you face these problems.
thank you very much sir,
please send me working scripts for send file attachment…
i am waiting for your response…
Sir,
how to send auto reply email to sender??
Please guide me.
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.
Only Demo link Is working….
given code is not working….
I have uploaded the file again please check this time its the same one which we are using for demo link.
thank you for reply
but
Same problem Sir Only Message change…..
If you are using it over the localhost than it will not work your work should be online
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…
Give me the link where you are using it
http://www.stallionflags.com/emailAttachment.php
it is a link for that file
Check your mail i have sent you the exact file which i am using at my demo check spam also
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.
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
hello dear i am having the same problem. if you got the solution of this thn please also give response.
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
try to check $upload_type=$_FILES[“upload”][“type”];
It will help you to put the validation
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
🙂
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.
The maqil is going to spam.
It depends over the mail provider
Hello.can u found any solution for my problem
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
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
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
what could be the problem…I am trying from couple of days
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
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….
http://www.dudekula.com/newdudekula/ex.php
Nice post vivek. I am trying it now if any issues i will comment..
I checked on hosting server to…But it reflecting same error
show me the link where you are using it
no yaar…demo is working perfectly…
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
Error in the sense…mail is not sending…
Please send the whole HTML
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!!!”;
}
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
Wait a moment i will send you the working code if you are getting some error with the working demo
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
What error it is showing can you send me the email photo to my mail id ……. vivek@simplyitsols.com
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…???
Check out the my new tutorial over it.
How to fetch data from database and display them as table
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….
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
Very useful Vivek.
-Motyar
Thank You
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 .
same method but use dont use
$headers .= “–“.$num.”–“;
because after this execution stop use
$headers .= “–“.$num.”\n”;
until last $headers .=”” call