Multiple Mail Attachments in PHP - php

I was wondering if I could pick your brain about something.
I have a mail script on my site that I can use to send emails with a single attachment. Sending a single attachment works just fine.
I want to be able to send an email with multiple attachments and I am running into problems doing so.
This is the file selection box I have in the form:
<input type="file" name="attachment[]" id="attachment[]" multiple onfocus="this.style.backgroundColor='#e7e7e7'" onblur="this.style.backgroundColor='#ffffff'"/>
Then, when the files are selected this is the php that handles it:
if (!empty($_FILES['attachment']['name']))
{
if(count($_FILES['attachment']['name'])>0)
{
$count = 0;
foreach ($_FILES['attachment']['name'] as $file)
{
$name_of_file = $_FILES['attachment']['name'][$count];
$file_name = $guid." - ".$name_of_file;
$temp_name = $_FILES['attachment']['tmp_name'][$count];
$file_type = $_FILES['attachment']['type'][$count];
$file_size = $_FILES['attachment']['size'][$count];
$count++;
if ($file_size > 2048000)
{
header ("refresh: 5; url=attach.php");
include ("header.php");
echo "File size is to big. Size must be no bigger than 2Mb. Please go <a href='attach.php'>back</a>";
include ("footer.php");
exit;
}
else
{
$pics = array(".bmp", ".gif", ".jpg", "jpeg", ".png"); //5
$docs = array(".doc", "docx", ".odt", ".pdf", ".ppt", "pptx", ".rtf", ".txt", ".xls", "xlsx"); //10
$misc = array(".csv", ".htm", "html", ".php", ".pkt", ".rar", ".sql", ".xpi", ".zip"); //9
$base = basename($file_name);
$extension = substr($base, strlen($base)-4, strlen($base));
$extension = strtolower($extension);
if (in_array($extension,$pics))
{
$target = "".FILES."/".FUP_PICS."/";
}
if (in_array($extension,$docs))
{
$target = "".FILES."/".FUP_DOCS."/";
}
if (in_array($extension,$misc))
{
$target = "".FILES."/".FUP_MISC."/";
}
$target = $target.$base;
$allowed_extensions = array(".bmp", ".csv", ".doc", "docx", ".gif", ".htm", "html",
".jpg", ".JPG", "jpeg", "JPEG", ".odt", ".pdf", ".php", ".pkt", ".png", ".ppt", "pptx",
".rtf", ".sql", ".txt", ".xls", "xlsx", ".zip"
);
if(in_array($extension,$allowed_extensions))
{
$from = mysql_real_escape_string($_POST['from']);
$emailto = mysql_real_escape_string($_POST['emailto']);
$bcc = mysql_real_escape_string($_POST['bcc']);
$subject = htmlspecialchars($_POST['subject']);
$message = htmlspecialchars($_POST['message'], ENT_NOQUOTES);
$message1 = htmlspecialchars_decode($_POST['message'], ENT_QUOTES);
if ($sendhash == 'Y')
{
$message1 .= "\n\nThe following is your unique message ID: ";
$message1 .= $guid;
$message1 .= "\n\nAttachment has been scanned for viruses and is virus free.";
$message1 .= "\n\nPlease make sure the first part of the file name matches the unique message ID. If it does not, please DO NOT open the file";
$message1 .= "\n\nTo verify the validity of the message, click the link below or copy and paste it into your browser:";
$message1 .= "\n\n ";
$message1 .= HTTP_PATH;
$message1 .= "verify.php?uid=";
$message1 .= urlencode($guid);
$message1 .= "\n\nPlease note, verification link expires on ";
$message1 .= $expirydate;
}
else
{
}
$message1 .= "\n\n--\nSent from Chris' Address Book";
foreach ($file as $files)
{
$files = $temp_name;
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
$header = "From: ".$from."\r\n";
$header .= "Reply-To: ".$from."\r\n";
$header .= "Bcc: ".$bcc."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format. \r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message1."\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$header .= $content."\r\n";
}
if ($_POST['emailto'] == '')
{
$sqlp=mysql_query("SELECT * FROM ".PERSON." JOIN contact on contact.personID = person.adbkid WHERE email1 = '$bcc' OR email2 = '$bcc'");
$num=mysql_numrows($sqlp);
}
else
{
$sqlp=mysql_query("SELECT * FROM ".PERSON." JOIN contact on contact.personID = person.adbkid WHERE email1 = '$emailto' OR email2 = '$emailto'");
$num=mysql_numrows($sqlp);
}
while ($row = mysql_fetch_array($sqlp))
{
$adbkid = $row['adbkid'];
$id = $row['id'];
}
if ($num == 0)
{
$selfid = "EMAILSA";
}
else
{
$selfid = $adbkid;
}
if (mail($emailto, $subject, "", $header))
{
if ($sendhash == 'Y')
{
$sql=mysql_query("INSERT INTO ".EMAILS." (emailfrom, emailto, bcc, subject, message, getthedate, gettime, randhash, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID) VALUES ('$from', '$emailto', '$bcc', '$subject', '$message', '$getthedate', '$gettime', '$guid', '$file_name', '$extension', '$showinsearch', '$expireit', '$siv', '$wv', '$selfid')");
$lastid=mysql_insert_id();
$sqlr=mysql_query("INSERT INTO ".HASH." (randhash) VALUES ('$guid')");
}
else
{
$sql=mysql_query("INSERT INTO ".EMAILS." (emailfrom, emailto, bcc, subject, message, getthedate, gettime, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID) VALUES ('$from', '$emailto', '$bcc', '$subject', '$message', '$getthedate', '$gettime', '$file_name', '$extension', '$showinsearch', '$expireit', '$siv', '$wv', '$selfid')");
$lastid=mysql_insert_id();
}
$sqlone = "INSERT INTO ".SENTFILES." (filename, filetype, fileext, filesize, filetempname, dateadded, timeadded, fileguid, sentmailid) VALUES ('$file_name', '$file_type', '$extension', '$file_size', '$temp_name', '$getthedate', '$gettime', '$guid', '$lastid')";
$expire = mysql_query("UPDATE ".EMAILS." SET showinverify = 0 WHERE expireit < CURDATE()");
if (!mysql_query($sqlone,$conn))
{
die("Error: " . mysql_error().".");
}
header ("refresh: 5; url=$url");
include ("header.php");
$ful = (move_uploaded_file($temp_name, $target)) ? "".$file_name." was uploaded to ".$target."" : "".$file_name.", was not uploaded. Please try a manual upload.";
echo "<title>Success sending email</title>";
echo "Your message has been successfully sent. Message details have been added to the database.<p>$ful";
include ("footer.php");
}
else
{
header ("refresh: 5; url=$url");
include ("header.php");
echo "<title>Error sending email</title>";
echo "There seems to be an error sending your email.";
include ("footer.php");
}
exit;
}
else
{
header ("refresh: 5; url=attach.php");
include ("header.php");
echo "File type is not allowed. Please go <a href='attach.php'>back</a>";
include ("footer.php");
exit;
}
}
}
}
The problem I run in to is when I try to send an email this way, I get the following error:
Warning: Invalid argument supplied for foreach() in /home/flattley/public_html/chriswilcox/cab/attach.php on line 150
Line 150 is this:
foreach ($file as $files)
I just don't have any idea where I am going wrong. If I don't have the foreach loop there it doesn't send or it will only send the first file.
I know I could use something like phpmailer, but I want to be able to do this on my own. I just can't see where I am going wrong.
I have tried the script on my local apache at home without mailing it and it uploads and moves multiple files just fine - as it does on my host. It's when I add the mailing option that it all goes pear shaped.
Any help you could offer would be most appreciated

If you look back at your code:
foreach ($_FILES['attachment']['name'] as $file)
$file is already a single file name. It is not an array. As mentioned my php documentation.
I see that in your code, you try to get the content of uploaded files. To do that, you can do something like this:
foreach($_FILES['attachment']['tmp_name'] as $eachFile){
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
$header = "From: ".$from."\r\n";
$header .= "Reply-To: ".$from."\r\n";
$header .= "Bcc: ".$bcc."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format. \r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message1."\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$header .= $content."\r\n";
}

Related

php html mail with attachment empty

I have this problem with PHP mail function:
I'm trying to sent an html email with a PDF file in attachment, the file is stored in a folder of mywebsite and created from me with mpdf, but when I send it the mail received has an attachment with size 0b.
this is the code:
<?
$attachment = "path_to_file_pdf.file.pdf";
if( file_exists($attachment)){
// File Exists
$size = filesize($attachment);
if( $size > 0 ){
//Alternative 1
$file = fopen($attachment,'rb');
$content = fread($file, $size);
fclose($file);
$content = chunk_split(base64_encode($content));
//Alternative 1
//$content = chunk_split(base64_encode(file_get_contents($attachment)));
$mailto = "example#maito.com";
$from_name = "MyDomainName";
$from_mail = "example#mydomain.com";
$replyto = "example#mydomain.com";
$uid = md5(uniqid(time()));
$subject = "e-mail subject here";
$message = "HTML MESSAGE HERE" ;
$filename = "file.pdf";
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"PHP-alt-".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--PHP-alt-".$uid."\r\n";
$header .= "Content-Type: text/html; charset=UTF-8\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--PHP-alt-".$uid."\r\n";
$header .= "Content-Type: application/pdf; name=\"".$filename."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; \r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--PHP-alt-".$uid."--";
if( #mail($mailto, $subject, "", $header) ){
echo "Mail SENT";
}else{
echo "ERROR - Mail error";
}
}else{
echo "ERROR- File size = 0";
}
}else{
echo "ERROR - File doesn't exist";
}
?>
The mail is sent correctly, so the file exist and its size is greater than 0b.
But when I receive the email in my emailbox it's all correct instead of the attachment that is present but empty.
I tryed both the 2 alternative of extracting the file content inserted in the code, but the result is the same.
Someone could help me?
I changed some headers configs. Try this:
<?
$attachment = "path_to_file_pdf.file.pdf";
if( file_exists($attachment)){
// File Exists
$size = filesize($attachment);
if( $size > 0 ){
//Alternative 1
$file = fopen($attachment,'rb');
$content = fread($file, $size);
fclose($file);
$content = chunk_split(base64_encode($content));
//Alternative 1
//$content = chunk_split(base64_encode(file_get_contents($attachment)));
$mailto = "example#maito.com";
$from_name = "MyDomainName";
$from_mail = "example#mydomain.com";
$replyto = "example#mydomain.com";
$uid = md5(uniqid(time()));
$subject = "e-mail subject here";
$message = "HTML MESSAGE HERE" ;
$filename = "file.pdf";
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"PHP-alt-".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--PHP-alt-".$uid."\r\n";
$header .= "Content-Type: text/html; charset=UTF-8\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--PHP-alt-".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--PHP-alt-".$uid."--";
if( #mail($mailto, $subject, "", $header) ){
echo "Mail SENT";
}else{
echo "ERROR - Mail error";
}
}else{
echo "ERROR- File size = 0";
}
}else{
echo "ERROR - File doesn't exist";
}
?>
Seen that I didn't receive answers, I only found one way to do that without problems, this way is to use PHPMailar class.
Thanx to the discussion:
Send attachments with PHP Mail()?

Creating excel from mysql and sending this as attachment email in php

I need to send an email with attachment, and that attachment file contain some data fetched from mysql database at the same time.
That problem is already asked and described here but there is no any working answer.
Can anyone have solution, than please answer.
while( $row = mysql_fetch_row( $sqlQuery ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
$cho = "$header\n$data";
echo $cho;
$headers = "From:abcdf.k#gmail.com(PFC Web Admin) \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: application/vnd.ms-excel";
$headers .= 'Content-Disposition: attachment; filename=Test.xls' . "\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "".$cho."\r\n";
$subject = 'Record November';
$mail = mail( 'abc.k#gmail.com', $subject, $msg, $headers );
if( $mail == true )
{
echo "Message successfully sent";
}
else
{
echo "Message could not be sent";
}
Excel is creating and have proper data but I need to mail this rather than download.
Try this,it's working
<?php
include_once('inc/dbConnect.inc.php');
error_reporting(E_ERROR);
$sql = mysql_query("SELECT * FROM tablename");
$row=mysql_fetch_assoc($sql);
$filename='temp/'.$filename.'.csv';
$fp=fopen($filename,"w");
$seperator="";
$comma="";
foreach($row as $name =>$value)
{
$seperator.=$comma.''.str_replace('','""',$name);
$comma=",";
}
$seperator.="\n";
$seperator;
fputs($fp,$seperator);
mysql_data_seek($sql,0);
while($row=mysql_fetch_assoc($sql))
{
$seperator="";
$comma="";
foreach($row as $name =>$value)
{
$seperator.=$comma.''.str_replace('','""',$value);
$comma=",";
}
$seperator.="\n";
fputs($fp,$seperator);
}
fclose($fp);
$my_file = $filename.'.csv';
$path = "temp/";
$from_name = "hhhhh";
$from_mail = "abc#gmail.com";
$mailto = "abc#gmail.com";
$subject = "This is a mail with attachment.";
$message = "Hi,\r\n do you got attachment?\r\n\r\Hara";
$replyto="haraprasad#lemonpeak.com";
$file = $path.$my_file;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
mail($mailto, $subject, "", $header)
?>
I don't see any attempt in your code to make a Excel file or an email with an attachment. I see those as two seperate questions.
When it comes to email attachments, it's best to use something that already exists, like:
http://swiftmailer.org
or
https://github.com/Synchro/PHPMailer
(order does not suggest anything)
For Excel the same thing applies, because with the CSV or XML versions of Excel files I always have problems. I have no suggestions though. I did find this more general site:
http://webdeveloperplus.com/php/5-libraries-to-generate-excel-reports-in-php/

PHP - Attach multiple files to email, files attached are blank?!!?

This is just a sample of the code, essentially I have a form with 4 files to upload. The files are successfully saved on my server in a designated folder. However, I obviously am not attaching them properly since they are empty....can anyone help?
Also, the attachments disply the directory name instead of the file name...what am I missing?
Many thanks!!!
<?php
$username= protect($_POST['username']);
$firstName= protect($_POST['firstName']);
$lastName= protect($_POST['lastName']);
$email= protect($_POST['email']);
$program= protect($_POST['program']);
$dob= protect($_POST['dob']);
$transcript= $_FILES['transcript'];
$resume= $_FILES['resume'];
$letterIntent= protect($_POST['letterIntent']);
$reference1= $_FILES['reference1'];
$reference2= $_FILES['reference2'];
$relevantExperience= protect($_POST['relevantExperience']);
$volunteerExperience= protect($_POST['volunteerExperience']);
$reasonsAbroad= protect($_POST['reasonsAbroad']);
$definitionSuccess= protect($_POST['definitionSuccess']);
$futureGoals= protect($_POST['futureGoals']);
$challengeYourself= protect($_POST['challengeYourself']);
$challengeDevelopment= protect($_POST['challengeDevelopment']);
if (isset($_FILES) && (bool) $_FILES) {
$allowed_ext = array('doc', 'pdf', 'txt', '');
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$path_parts = pathinfo($file_name);
$file_ext = $path_parts['extension'];
if(!in_array($file_ext, $allowed_ext)) {
die ("extension for file $file_name not allowed");
}
if($file_size > 2097152) {
die ("File size must be under 2MB");
}
$server_file = "wp-content/uploads/application-documents";
move_uploaded_file($file_tmp, "$server_file/$file_name");
array_push($files, $server_file);
}
$to = ".....#gmail.com";
$from = "$email";
$subject ="Application from $firstName $lastName with attachments";
$msg = "hello";
$headers = "From: $from";
//define email boundaries
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
foreach($files as $file) {
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
}
?>
I know it's not the answer to your post, but after struggling with this kind of problems in the past, I gave up and used PHPMailer. If you still want to roll your own, you should take a look at its source code.

PHP mail multiple attach

I writte this code to send multiple attachments:
$tablica_plikow=$_FILES["file"]; //array of files
if(!empty($tablica_plikow['name'])){///if attachment
$uid = md5(uniqid(time()));
$header = "From: od\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-2\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .=win2iso( $_POST['tresc'])."\r\n\r\n\r\n\r\n\r\n\r\n";///message
$header .= "--".$uid."\r\n";
for($i=0; $i<count($tablica_plikow['name']); $i++){
if ($tablica_plikow["error"][$i] > 0)
{ $komunikat = "<img src=\"img_panel/bttn_error.gif\">"."Return Code: " . $tablica_plikow["error"][$i] ;
}
if (file_exists("zalacznik/" . $tablica_plikow["name"][$i]))
{
$komunikat = "<img src=\"img_panel/bttn_error.gif\">"."Return Code: " . $tablica_plikow["name"][$i]. " already exists. " ;
}
else
{
if(is_uploaded_file($tablica_plikow["tmp_name"][$i])) {
move_uploaded_file($tablica_plikow["tmp_name"][$i],
"zalacznik/" . $tablica_plikow["name"][$i]);
$komunikat = "<img src=\"img_panel/bttn_info.gif\">" . "zalacznik/" . $tablica_plikow["name"][$i];
$target_path="zalacznik/" . $tablica_plikow["name"][$i];
$file = "zalacznik/".$tablica_plikow["name"][$i];
$file_size = filesize($file);
$handle = fopen($file, "rb");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$name = basename($file);
$header .= "Content-Type: ".$tablica_plikow["type"][$i]." name=\"".$tablica_plikow["name"][$i]."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\n\r".$content."\r\n\r\n";;
$header .= "Content-Disposition: attachment; filename=\"".$tablica_plikow["name"][$i]."\"\r\n\r\n";
// $header .= $content."\r\n\r\n";
$header .= "--".$uid."-- \r\n";
}
}
}
if (mail("mail#moj.com", $_POST['tytul'], "", $header)) {
$komunikat = "<img src=\"img_panel/bttn_info.gif\">mail send";
} else {
$komunikat = "<img src=\"img_panel/bttn_error.gif\">error";
}
But when I send an email with two or more attachments, receive only one file.This file is a concatenation of all attachments. But the first part of the file is the first attachment, and other parts are just hashmap other files.
I would use a library eg.
Zend_Mail
Pear Mail_Mime
I'd like to advise you to use PHP Mailer.
I advice you use standard and tested mailing lib such as phpMail
It has been discussed here before Please see regarding email with attachment in php
Thanks
:)

MIME header appearing in the email message body

I have a problem sending php email using the code below. The MIME heades keep apearing in the message and the attachment appears as scribble text in the mesage body not as attachment. what could be the problem
<?php
session_start();
require_once("includes/functions.php");
require_once("includes/dbconnect.php");
require_once("Mail/mailfunctions.php");
//function_to_be_applied($finaldest_email, $message, $subject, $fromname, $fromemail, $replyto )
function function_to_be_applied($finaldest_email, $key){
//require_once "Mail.php" ;
global $fromemail;
global $message;
global $fromname;
global $subject;
global $replyto;
global $seconds;
global $reprt;
global $headers;
$to = $finaldest_email;
$from = "".$fromname." <$fromemail>";
$subject = $subject;
if(mail($to, $subject, $message, $headers)) {
sleep($seconds);
$reprt .= "Message successfully sent to: ". $to."<br />";
} else {
$reprt .= "Message not successfully sent to: ". $to."<br />";
}
}
if(isset($_POST['submit']))
{
$errors_val = array();
$required_fields = array("subject", "fromemail", "message", "dest_email");
foreach($required_fields as $fieldname)
{
if( !isset($_POST[$fieldname]) || ( empty($_POST[$fieldname]) &&(!is_int($_POST[$fieldname])) ))
{
if($fieldname == "subject")
{$errors_val[0] = "-Sending email without SUBJECT is not allowed";}
if($fieldname == "fromemail")
{$errors_val[1] = "-Sending email without a FROM EMAIL is not allowed";}
if($fieldname == "message")
{$errors_val[2] = "-Sending an empty message is not allow";}
if($fieldname == "dest_email")
{$errors_val[3] = "-There must be at least one email in the destination email address";}
}
}
if(empty($errors_val)){
$errors = array();
if(false == validate_email(trim($_POST['fromemail']))){
$errors[0] = "FROM EMAIL is invalid";
}
if(false == validate_email(trim($_POST['replyto']))){
$errors[1] = "REPLY TO EMAIL is invalid";}
if(!is_numeric(trim($_POST['seconds']))){
$errors[2] = "Seconds between messages must be a number";}
$allowtypes = array("doc", "pdf", "txt", "zip", "gif", "jpeg", "jpg"); //the type of file can be attached
$max_file_size="100"; //describes the size that cab be attached
// checks that we have a file
if((!empty($_FILES["attachment"])) && ($_FILES["attachment"]["error"] == 0)) {
//set a variable $attached = 1
$attached = 1;
// 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[3]="Invalid extension for your file: <strong>".$filename."</strong>";
unset($attached);
// check the size of each file
} elseif($filesize > $max_bytes) {
$errors[4]= "Your file: <strong>".$filename."</strong> is to big. Max file size is ".$max_file_size."kb.";
unset($attached);
}
}
if(empty($errors)){
//generate a unique boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
if(isset($_POST['seconds']) && ($_POST['seconds'] != ""))
{$seconds = $_POST['seconds'];}else{$seconds = 0.5;}
$subject = trim($_POST['subject']);
$fromname = trim($_POST['fromname']);
$fromemail = trim($_POST['fromemail']);
$from = stripslashes($fromname)."<".stripslashes($fromemail).">";
$emailmessage = trim($_POST['message']);
$replyto = trim($_POST['replyto']);
$dest_email = trim($_POST['dest_email']);
$emailarray = explode("\r\n", $dest_email, 400);
$finaldest_email = array_unique($emailarray );
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To:" . $replyto . "\r\n";
$headers .= "Mime-Version: 1.0\r\n";
$headers .= " Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
//attachment
if(isset($attached)){
$fileatt = $_FILES["attachment"]["tmp_name"];
$fileatt_type = $_FILES["attachment"]["type"];
$fileatt_name = $_FILES["attachment"]["name"];
if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$data = file_get_contents($fileatt);
//$file = fopen($fileatt,'rb');
//$data = fread($file,filesize($fileatt));
//fclose($file);
// Base64 encode the file data
$finaldata = chunk_split(base64_encode($data));
}
$message = "--{$mime_boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "{$emailmessage}\r\n";
$message .= "--{$mime_boundary}\r\n";
$message .= "Content-Type: {$fileatt_type}; name=\"{$fileatt_name}\"\n\n".
"Content-Transfer-Encoding: base64\n\n";
$message .= "Content-Disposition: attachment; filename=\"{$fileatt_name}\"\n\n";
$message .= "{$finaldata} \r\n--{$mime_boundary}--\r\n";
}elseif(!isset($attached)){
$message = "--{$mime_boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\" \r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "{$emailmessage}\r\n";
$message .= "--{$mime_boundary}--\r\n";
}
$reprt = "Preparing to send message..<br />";
if( true == array_walk($finaldest_email, 'function_to_be_applied' )){
$numberofemailsent = count($finaldest_email);
}else{echo "No email sent";}
}else{$string = implode("<br /> -" , $errors); $error_message = $string; }
}else{$string = implode("<br /> -" , $errors_val); $error_message = $string; }
}
?>
Don't generate your own mime emails. Use PHPMailer or Swiftmailer and reduce a huge chunk of that script down to maybe 10 lines of code.
As well, don't verify file types by looking at filenames. It's trivial to forge a filename AND the client-specified mime type. Always use server-side mime verification instead.

Categories