I have a chunk of code that is taking a user uploaded file, and processing it. When the user uploads a .xls file, the file is shredded. I suspect it has something to do with the MIME but I don't know too much about them. Any help would be appreciated.
<?php include ("header1.html") ?>
<!--- End --->
<tr height="100%">
<td align="center" valign="top" style="background-image: url('images/midbg.jpg'); background-repeat:repeat-x; padding-top: 25px; " bgcolor="#e6e6e6" >
<!--- Body begins here --->
<table width="725" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="100%" valign="top">
<table style="margin-left:130px; margin-top:20px;">
<tr><td>
<p><strong style="font-size:12px"> </strong> </p>
<?php
$userName = $session->userName;
if ($handle = opendir('fileuploads/'.$userName)) {
//echo "Directory handle: $handle\n";
// echo "Files:\n";
$path = 'fileuploads/'.$userName.'/';
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if(($file != "Thumbs.db") && ($file != ".")&& ($file != ".."))
{
$attachment[] = $path.$file;
}
}
// echo '<p><b>Current total = '.$totalsize.'K</b></p>';
closedir($handle);
}
function fileName($inputfile,$userName)
{
$separator = '/'.$userName.'/';
$output = split ($separator, $inputfile);
return $output[1];
}
$files = $attachment;
//print_r($files);
// email fields: to, from, subject, and so on
$memberEmails = $_POST['emails'];
$bcc = $_POST['bccAddress'];
if ($bcc != '')
{
$bcc = $memberEmails . ',' . $bcc;
}
else
{
$bcc = $memberEmails;
}
$to = $_POST['toAddress'];
if($to != '')
{
$to = $userName. "#place.com,". $to;
}
else
{
$to = $userName. "#place.com";
}
$cc = $_POST['ccAddress'];
$from = $userName. "#place.com";
$subject =$_POST['subject'];
$message = $_POST['content'];
$message = str_replace('\"', '"',$message);
$headers = "From: ".$_SESSION['fullName']. "<$from>\n";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
if ($cc != '')
{
$headers .= "CC: ". $cc ."\n";
}
if ($bcc != '')
{
$headers .= "BCC: ". $bcc ."\n";
}
$headers .= "MIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\" {$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
if( count($files) > 0)
{
$message .= "--{$mime_boundary}\n";
}
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$fileName= fileName($files[$x],$userName);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$fileName\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$y = $x +1;
if ( count($files) > $y)
{
$message .= "--{$mime_boundary}\n";
}
}
$ok = #mail($to, $subject, $message, $headers);
if ($ok)
{
$logFile = "log/tmlog.log";
$logHandle = fopen($logFile, 'a');
$logData = "[" . date('Y-m-d H:i:s') . "] " .$userName. " - message sent successfully (". $to. ",".$bcc .",". $cc.")\n";
fwrite($logHandle, $logData);
fclose($logHandle);
echo '<META HTTP-EQUIV="Refresh" CONTENT="0;URL=fileuploads/sendRm.php?msg=sent">';
}
else
{
$logFile = "log/tmlog.log";
$logHandle = fopen($logFile, 'a');
$logData = "[" . date('Y-m-d H:i:s') . "] " .$userName. " - message failed\n";
fwrite($logHandle, $logData);
fclose($logHandle);
echo '<META HTTP-EQUIV="Refresh" CONTENT="0;URL=fileuploads/sendRm.php?msg=fail">';
}
}
?>
At what stage is the file damaged? At the server side immediately after the file upload, or at the email client end when the file has been emailed?
Here is the code rewritten to make it readable/standards compliant...
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
if ($cc != '') $headers .= "Cc: $cc\r\n";
if ($bcc != '') $headers .= "Bcc: $bcc\r\n";
$headers .= "MIME-Version: 1.0\r\n"
. "Content-Type: multipart/mixed; boundary=\"$mime_boundary\"\r\n";
// multipart boundary
$message = "This is a multi-part message in MIME format.\r\n"
. "--$mime_boundary\r\n"
. "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
. "Content-Transfer-Encoding: 7bit\r\n"
. "\r\n"
. $message . "\r\n"
. "--$mime_boundary";
if (count($files)) { // Add attachments
for ($x = 0; $x < count($files); $x++){
$data = chunk_split(base64_encode(file_get_contents($files[$x])));
$fileName = fileName($files[$x], $userName);
$message .= "\r\n"
. "Content-Type: application/octet-stream\r\n"
. "Content-Disposition: attachment; filename=\"$fileName\"\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. "\r\n"
. $data . "\r\n"
. "--$mime_boundary";
}
}
$message .= '--';
Related
this php code is correct.this code having no errors but when user submits form ,in received email only shows file attachment in email.it does not show all input fields values. what is required to do ???
<?php
if(isset($_FILES) && (bool) $_FILES) {
$AllowedExtensions = ["pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt"];
$files = [];
$server_file = [];
foreach($_FILES as $name => $file) {
$file_name = $file["name"];
$file_temp = $file["tmp_name"];
foreach($file_name as $key) {
$path_parts = pathinfo($key);
$extension = strtolower($path_parts["extension"]);
if(!in_array($extension, $AllowedExtensions)) { die("Extension not allowed"); }
$server_file[] = "uploads/{$path_parts["basename"]}";
}
for($i = 0; $i<count($file_temp); $i++) { move_uploaded_file($file_temp[$i], $server_file[$i]); }
}
$from = "example#gmail.com";
$headers = "From: $from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n";
$message .= "--{$mime_boundary}\n";
$FfilenameCount = 0;
for($i = 0; $i<count($server_file); $i++) {
$afile = fopen($server_file[$i],"rb");
$data = fread($afile,filesize($server_file[$i]));
fclose($afile);
$data = chunk_split(base64_encode($data));
$name = $file_name[$i];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
}
/** Your submit block **/
if(isset($_POST['submit']))
{
$name = htmlspecialchars($_REQUEST['name']);
$email = htmlspecialchars($_REQUEST['email']);
$mobile = htmlspecialchars($_REQUEST['mobile']);
$company = htmlspecialchars($_REQUEST['company']);
$qty = htmlspecialchars($_REQUEST['qty']);
$msg = htmlspecialchars($_REQUEST['msg']);
$subject = "Order Information";
$message .= "Name: " . $name . "\n";
$message .= "Email: " . $email . "\n";
$message .= "ContactNo: " . $mobile . "\n";
$message .= "Company: " . $company . "\n";
$message .= "Quantity: " . $qty . "\n";
$message .= "Message: " . $msg . "\n";
if(mail($from, $subject, $message, $headers)) {
echo 'thank you';
}
else {
echo 'error';
}
}
?>
I think you need to convert part where you send post data to multipart also. Otherwise your mail client will probably ignore it (I think you may find it at the bottom of mail in "view mail source" mode).
It should be something like (only $_POST part):
if(isset($_POST['submit']))
{
$name = htmlspecialchars($_REQUEST['name']);
$email = htmlspecialchars($_REQUEST['email']);
$mobile = htmlspecialchars($_REQUEST['mobile']);
$company = htmlspecialchars($_REQUEST['company']);
$qty = htmlspecialchars($_REQUEST['qty']);
$msg = htmlspecialchars($_REQUEST['msg']);
$to="amar.ghodke30#gmail.com";
$subject = "Order Information";
$message .= "--{$mime_boundary}\n"; //$mime_boundary should be the same as for attachments.
$message .= "Content-type: text/plain;charset=utf-8\n\n";
$message .= "Name: " . $name . "\n";
$message .= "Email: " . $email . "\n";
$message .= "ContactNo: " . $mobile . "\n";
$message .= "Company: " . $company . "\n";
$message .= "Quantity: " . $qty . "\n";
$message .= "Message: " . $msg . "\n";
$message .= "--{$mime_boundary}\n\n";
if(mail($from, $subject, $message, $headers)) {
echo 'thank you';
}
else {
echo 'error';
}
}
On submitting form, user is taken to following action page. On this page email is sent along with attachment.
I am receiving email and attachment but header('Location: ...') is not working. Action page is not redirecting and keeps on showing loading sign in broweser. On debugging found no errors on page.
*This problem only comes when a file is attached.
PHP form processing page:-
<?php
require_once 'settings.php';
if (( isset($_POST)) && ( empty($_POST))) {
header('Location: ../career.html');
die ;
}
foreach ($_POST as $key => $value) {
if (empty($value)) {
header('Location: ../career.html#error');
die ;
}
if (ini_get('magic_quotes_gpc')) {
$value = stripslashes($value);
}
$val[$key] = htmlspecialchars(strip_tags(trim($value)));
}
$tmp = date('r');
$message = "<!DOCTYPE html><html><body>";
$message .= "<p><strong>Name: </strong>{$val['name']}</p>";
$message .= "<p><strong>Email: </strong>{$val['email']}</p>";
$message .= "<p><strong>Phone: </strong>{$val['phone']}</p>";
$message .= "<p><strong>Work Experience: </strong>{$val['workex']}</p>";
$message .= "<p><strong>Career: </strong>{$val['career']}</p><br>";
$message .= "<p> <i> This form was submited from {$_SERVER["HTTP_HOST"]} on $tmp by IP {$_SERVER['REMOTE_ADDR']} </i> </p>";
$message .= "</body></html>";
$uid = md5(uniqid(time()));
$header = "From: " . $val['name'] . " <" . $val['email'] . ">\r\n";
$header .= "Reply-To: " . $val['name'] . " <" . $val['email'] . ">\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/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message . "\r\n\r\n";
$header .= "--" . $uid . "\r\n";
if (isset($_FILES["file"]["name"]) && !empty($_FILES["file"]["name"])) {
if ($_FILES["file"]["size"] > $fileSize) {
header('Location: ../career.html?#error-size');
die ;
}
$filename = $_FILES["file"]["name"];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($ext, $fileType)) {
header('Location: ../career.html?#error-type');
die ;
}
$content = chunk_split(base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$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 .= "--" . $uid . "--";
}
if (mail($mailTo, $careerSubject, $message, $header)) {
header('Location: ../career.html#success');
die ;
} else {
header('Location: ../career.html?#error');
die ;
}
?>
try remove "..", like header('Location: /career.html#error');
the following code works just fine, but when users submitting without any attachments the page gives error alert and nothing is happened, ther mast any condition that i'm missing, someone knows what i need to add?
<?php
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files, array('temp_name' => $temp_name, 'file_name' => $file_name));
}
// email fields: to, from, subject, and so on
$to = "dorozenman#gmail.com";
$from = $_POST['sender_email'];
$subject ="בקשה להצעת עבודה מ" . $_POST['sender_name'] .' '. $_POST['sender_suname'];
$message = 'שם: '. $_POST['sender_name'] . "\r\n" . 'שם משפחה: ' . $_POST['sender_suname'] . "\r\n" . 'תאריך לידה: ' . $_POST['sender_Bday'] . "\r\n" . 'עיסוק נוכחי: ' . $_POST['sender_work'] . "\r\n" . 'טלפון: ' . $_POST['sender_phone'] . "\r\n" . 'מייל: ' . $_POST['sender_email'] . "\r\n" . 'טקסט חופשי: ' . $_POST['sender_way'] ;
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$temp_name = $files[$x]['temp_name']; // temporary file location
$file_name = $files[$x]['file_name']; // filename
$file = fopen($temp_name,"rb");
$data = fread($file,filesize($temp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file_name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$file_name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) { ?>
<script language="javascript" type="text/javascript">
alert('הבקשה נשלחה! שיהיה לך בהצלחה!');
top.window.location = 'https://www.facebook.com/gingereilat';
</script>
<?php } else { ?>
<script language="javascript" type="text/javascript">
alert('שגיאה במערכת בצעו פעולה זאת מאוחר יותר או צרו קשר dorozenman#gmail.com');
top.window.location = 'https://www.facebook.com/gingereilat';
</script>
<?php
}
}
?>
your whole code in following if clause
if(isset($_FILES) && (bool) $_FILES) {
check where its applicable.
Please post the error messages! That makes answering your question a lot easier.
Just reading the code, an obvious problem is var $files is only initialised inside the first if statement, but then you use it in the for loop.
Move the line $files = array(); to the top of your script so it is always initialised as an empty array.
I'm trying to move a file after a batch job e-mail has been sent into the "OLD" folder.
I have successfully determined the code to do so. Right now the file is called monthly_mssql, I'm trying to rename the file to monthly_mssql_mmmyyyy.
With the month and year added to the end of the file I can keep track of determining which reports are for which month. How would I edit the existing command file?
MY CODE FOR CMD FILE:
REM The report is generated automatically and must be sent at 9:50 AM of the first Monday of every month, file is located
REM in C:\Reports\mssql\Monthly_Stats
"C:\Program Files\xampp\php\php.exe" "c:\htdocs\MultipleReport\monthly_smurfreport_email.php"
move C:\Smurf_Reports\mssql\Monthly_Stats\monthly_mssql.csv C:\Smurf_Reports\mssql\Monthly_Stats\old
MY CODE FOR PHP FILE:
$dirpath = "C:/Reports/mssql/Monthly_Stats/";
if ($handle = opendir($dirpath ))
{
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 8bit\n\n" .
$message_text . "\n\n";
$email_message .= "--{$mime_boundary}\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle)))
{
if (strpos($entry, '.csv',1))
{
$filepath = "";
$filesize = 0;
$filepath = $dirpath."".$entry;
$filesize = filesize ($filepath);
if (file_exists($filepath) && $filesize > 1)
{
$fileatt = $filepath;
$fileatt_name = $entry;
$fileatt_type = "application/octet-stream";
$message_text .= "<P>Hi</P>";
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "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";
$email_message .= "--{$mime_boundary}\n";
}
$email_from = "k.j#yahoo.com";
// $email_to = "k.j#yahoo.com";
$email_to = "k.j#yahoo.com";
$lastMonth = date('F-Y',strtotime('last month'));
$email_subject = "($lastMonth) Report for MS-SQL.";
$headers .= "From: ".$email_from."\r\n";
echo $filepath."</br>";
}
}
closedir($handle);
$ok = #mail($email_to, $email_subject, $email_message, $headers);
}
/*if (file_exists($filename) && $size > 228 && $EmailAdd <> "")
{
$fileatt = $filename;
$fileatt_name = $groupname.".csv";
if ($uemail <> "")
$email_from = $uemail;
else
$email_from = $username."#yahoo.com";
$email_to = $email_from;
$email_subject = " Messages for Priority '".$p."' - ".$groupname." - ".$displaydate;
$headers .= "From: ".$email_from. "\r\n";
$headers .= "Cc: ".$EmailAdd. "\r\n";
$headers .= "Bcc: k.j#yahoo.com";
$email_message .= "<P>Hi</P>";
$email_message .= "<P><B>Please find attached Monthly Smurf Report Stats."</U></B>\n";
$email_message .= "<P><P>Thanks,<P>;
set_error_handler("myErrorHandler");
$ok = #mail($email_to, $email_subject, $email_message, $headers);
if ($ok)
{
unlink($filename);
}
else
{
$file = "C:/Reports/Operation/Daily_Stats/smtperrlog.txt";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
fclose($fh);
$stderr = fopen ('C:/Reports/Operation/Daily_Stats/smtperrlog.txt', 'w+');
fwrite($stderr,"");
fclose($stderr);
$email_fromerr = "k.j#yahoo.com";
$email_toerr = "k.j#yahoo.com";
$email_subjecterr = "Monthly Stats";
$email_messageerr = $contents;
$headerserr .= "From: ".$email_fromerr. "\r\n";
#mail($email_toerr, $email_subjecterr, $email_messageerr, $headerserr);
}
}
*/
$message_text = "";
$p = "";
$EmailAdd = "";
$headers = "";
$counter = 0;
In my opinion, moving it with a batch file would be unnecessary. I would move it directly in PHP with the rename() method. You can append a date at the end of the file with date().
An example of this would be:
rename("C:\Smurf_Reports\mssql\Monthly_Stats\monthly_mssql.csv", "C:\Smurf_Reports\mssql\Monthly_Stats\old\monthly_mssql_" . date("m_Y") . ".csv");
Edit
$cMonth = intval(date("m")); //Retrieves current month, converts to int value
$lastMonth = ($cMonth == 1 ? "12" : $cMonth - 1); //If it's January, let's set the month to December
$cYear = ($cMonth == 1 ? intval(date("Y")) - 1 : date("Y")); //If it's January, let's also set the year back by one so the dates match up
rename("C:\Smurf_Reports\mssql\Monthly_Stats\monthly_mssql.csv", "C:\Smurf_Reports\mssql\Monthly_Stats\old\monthly_mssql_" . $lastMonth . "_" . $cYear . ".csv");
<?php
// array with filenames to be sent as attachment
$files = array("sendFiles.php");
// email fields: to, from, subject, and so on
$to = "dfjdsoj#googlemail.com";
$from = "mail#mail.com";
$subject ="My subject";
$message = "A logo has been sen't by". $_SESSION['loggedin_business_name'];
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
echo sizeof($files);
$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 get an email with my sendfiles.php then a text file ATT00424.txt. The number changes everytime. Send it to my gmail and it's fine! Very Strange!
$files = array("sendFiles.php");
// email fields: to, from, subject, and so on
$to = "hdfiuhufsadhfu#yaho.com";
$from = "mail#mail.com";
$subject ="My subject";
$message = "A logo has been sen't by". $_POST['loggedin_business_name'];
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\r\nMIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\r\n" . "--{$mime_boundary}\r\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n" . "Content-Transfer-Encoding: 7bit\r\n" . $message . "\r\n";
$message .= "--{$mime_boundary}\r\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\r\n" . " name=\"$files[$x]\"\r\n" .
"Content-Disposition: attachment;\r\n" . " filename=\"$files[$x]\"\r\n" .
"Content-Transfer-Encoding: base64\r\n" . $data . "\r\n";
$message .= "--{$mime_boundary}\r\n";
}
Adding CRLF in the code fixed the attachment issue however now the message "A logo has been sen't by" has disappeared. Why is this?
Use phpMailer()
<?php
require_once('phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSendmail(); // telling the class to use SendMail transport
try {
$mail->AddReplyTo('email#example.com', 'First Last');
$mail->AddAddress('John#example.com', 'John Doe');
$mail->SetFrom('email#example.com', 'First Last');
$mail->Subject = "Subject Line";
$mail->AltBody = "Alternate Text"; // optional, comment out and test
$mail->WordWrap = 50; // set word wrap
$mail->Body = "This is the body of the email";
$mail->IsHTML(true); // send as HTML
// Single or Multiple File Attachments
$mail->AddAttachment('../path-to-file.pdf', 'File-Name.pdf');
$mail->Send(); // Try to send email
//echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
// end try
?>
Try having CRLF (\r\n) line breaks. Outlook can be a bit funny about these things.
You can use this class
<?php
/*
Usage
=====
set $this->to
set $this->subject
set $this->message (with html tags)
set $this->from (Optional)
set $this->cc (this can be an array or a variable) (Optional)
set $this->bcc (this can be an array or a variable) (Optional)
set $this->reply_to (Optional)
set $this->return_path (Optional)
set $this->x_mailer (Optional)
set $this->attach_file_name (this can be an array or a variable) (Optional)
$this->SendMail();
This function returns an array of 2 elements which e[0] = true (on success) or false and e[1] = message
*/
class EMail
{
var $to;
var $from;
var $cc;
var $bcc;
var $reply_to;
var $return_path;
var $x_mailer;
var $subject;
var $message;
var $attach_file_name;
function EMail()
{
$this->to = "";
$this->subject = "";
$this->message = "";
$this->from = "Administrator <admin#" . $_SERVER['SERVER_NAME'] . ">";
$this->cc = "";
$this->bcc = "";
$this->reply_to = $this->from;
$this->return_path = $this->from;
$this->x_mailer = "PHP v" . phpversion();
$this->attach_file_name = "";
}
function makeFileName ($url)
{
$pos=true;
$PrePos=0;
while (!$pos==false)
{
$pos = strpos($url,'\\',$PrePos);
if ($pos===false)
{
$temp = substr($url,$PrePos);
}
else
{
$PrePos = $pos + 1;
}
}
return $temp;
}
function processAttachment()
{
if(is_array($this->attach_file_name))
{
$s = sizeof($this->attach_file_name);
for($i=0; $i<$s; $i++)
{
if($this->attach_file_name[$i] != "")
{
$handle = fopen($this->attach_file_name[$i], 'rb');
$file_contents = fread($handle, filesize($this->attach_file_name[$i]));
$Attach['contents'][$i] = chunk_split(base64_encode($file_contents));
fclose($handle);
$Attach['file_name'][$i] = $this->makeFileName ($this->attach_file_name[$i]);
$pos=true;
$PrePos=0;
while (!$pos==false)
{
$pos = strpos($this->attach_file_name[$i], '.', $PrePos);
if ($pos===false)
{
$Attach['file_type'][$i] = substr($this->attach_file_name[$i], $PrePos);
}
else
{
$PrePos = $pos+1;
}
}
}
}
return $Attach;
}
else
{
$handle = fopen($this->attach_file_name, 'rb');
$file_contents = fread($handle, filesize($this->attach_file_name));
$Attach['contents'][0] = chunk_split(base64_encode($file_contents));
fclose($handle);
$Attach['file_name'][0] = $this->makeFileName ($this->attach_file_name);
$pos=true;
$PrePos=0;
while (!$pos==false)
{
$pos = strpos($this->attach_file_name, '.', $PrePos);
if ($pos===false)
{
$Attach['file_type'][0] = substr($this->attach_file_name, $PrePos);
}
else
{
$PrePos = $pos+1;
}
}
}
return $Attach;
}
function validateMailAddress($MAddress)
{
if (eregi("#", $MAddress) && eregi(".", $MAddress))
{
return true;
}
else
{
return false;
}
}
function Validate()
{
if(is_array($this->to))
{
$msg[0] = false;
$msg[1] = "You should provide only one receiver email address";
return $msg;
}
if(is_array($this->from))
{
$msg[0] = false;
$msg[1] = "You should provide only one sender email address";
return $msg;
}
if($this->to == "")
{
$msg[0] = false;
$msg[1] = "You should provide a receiver email address";
return $msg;
}
if($this->subject == "")
{
$msg[0] = false;
$msg[1] = "You should provide a subject for your email";
return $msg;
}
if($this->message == "")
{
$msg[0] = false;
$msg[1] = "You should provide message for your email";
return $msg;
}
if(!$this->validateMailAddress($this->to))
{
$msg[0] = false;
$msg[1] = "Receiver E-Mail Address is not valid";
return $msg;
}
if(!$this->validateMailAddress($this->from))
{
$msg[0] = false;
$msg[1] = "Sender E-Mail Address is not valid";
return $msg;
}
if(is_array($this->cc))
{
$s = sizeof($this->cc);
for($i=0; $i<$s; $i++)
{
if(!$this->validateMailAddress($this->cc[$i]) && $this->cc[$i] != "")
{
$msg[0] = false;
$msg[1] = $this->cc[$i] . " is not a valid E-Mail Address";
return $msg;
}
}
}
else
{
if(!$this->validateMailAddress($this->cc) && $this->cc[$i] != "")
{
$msg[0] = false;
$msg[1] = "CC E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->bcc))
{
$s = sizeof($this->bcc);
for($i=0; $i<$s; $i++)
{
if(!$this->validateMailAddress($this->bcc[$i]) && $this->bcc[$i] != "")
{
$msg[0] = false;
$msg[1] = $this->bcc[$i] . " is not a valid E-Mail Address";
return $msg;
}
}
}
else
{
if(!$this->validateMailAddress($this->bcc) && $this->bcc[$i] != "")
{
$msg[0] = false;
$msg[1] = "BCC E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->reply_to))
{
$msg[0] = false;
$msg[1] = "You should provide only one Reply-to address";
return $msg;
}
else
{
if(!$this->validateMailAddress($this->reply_to))
{
$msg[0] = false;
$msg[1] = "Reply-to E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->return_path))
{
$msg[0] = false;
$msg[1] = "You should provide only one Return-Path address";
return $msg;
}
else
{
if(!$this->validateMailAddress($this->return_path))
{
$msg[0] = false;
$msg[1] = "Return-Path E-Mail Address is not valid";
return $msg;
}
}
$msg[0] = true;
return $msg;
}
function SendMail()
{
$mess = $this->Validate();
if(!$mess[0])
{
return $mess;
}
# Common Headers
$headers = "From: " . $this->from . "\r\n";
$headers .= "To: <" . $this->to . ">\r\n";
if(is_array($this->cc))
{
$headers .= "Cc: " . implode(", ", $this->cc) . "\r\n";
}
else
{
if($this->cc != "")
$headers .= "Cc: " . $this->cc . "\r\n";
}
if(is_array($this->bcc))
{
$headers .= "BCc: " . implode(", ", $this->bcc) . "\r\n";
}
else
{
if($this->bcc != "")
$headers .= "BCc: " . $this->bcc . "\r\n";
}
// these two to set reply address
$headers .= "Reply-To: " . $this->reply_to . "\r\n";
$headers .= "Return-Path: " . $this->return_path . "\r\n";
// these two to help avoid spam-filters
$headers .= "Message-ID: <message-on " . date("d-m-Y h:i:s A") . "#".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: " . $this->x_mailer . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
# Tell the E-Mail client to look for multiple parts or chunks
$headers .= "Content-type: multipart/mixed; boundary=AttachMail0123456\r\n";
# Message Starts here
$msg = "--AttachMail0123456\r\n";
$msg .= "Content-type: multipart/alternative; boundary=AttachMail7890123\r\n\r\n";
$msg .= "--AttachMail7890123\r\n";
$msg .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
$msg .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$msg .= strip_tags($this->message) . "\r\n";
$msg .= "--AttachMail7890123\r\n";
$msg .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$msg .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$msg .= "<html><head></head><body>" . $this->message . "</body></html>\r\n";
$msg .= "--AttachMail7890123--\r\n";
if($this->attach_file_name != "" || is_array($this->attach_file_name))
{
$Attach = $this->processAttachment();
$s = sizeof($Attach['file_name']);
for($i=0; $i<$s; $i++)
{
# Start of Attachment chunk
$msg .= "--AttachMail0123456\r\n";
if ($Attach['file_type'][$i]=="gif")
{
$msg .= "Content-Type: image/gif; name=" . $Attach['file_name'][$i] . "\r\n";
}
elseif ($Attach['file_type'][$i]=="jpg" || $Attach['file_type'][$i]=="jpeg")
{
$msg .= "Content-Type: image/jpeg; name=" . $Attach['file_name'][$i] . "\r\n";
}
else
{
$msg .= "Content-Type: application/file; name=" . $Attach['file_name'][$i] . "\r\n";
}
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "Content-Disposition: attachment; filename=" . $Attach['file_name'][$i] . "\r\n\r\n";
$msg .= $Attach['contents'][$i] . "\r\n";
}
}
$msg .= "--AttachMail0123456--";
$result = mail($this->to, $this->subject, $msg, $headers);
if ($result)
{
$mess[0] = true;
$mess[1] = "Mail Successfully delivered";
}
else
{
$mess[0] = false;
$mess[1] = "Mail can not be send this time. Please try latter.";
}
return $mess;
}
}
?>
$from = stripslashes("from#demo.com");
$to = stripslashes("to#to.com");
$subject =$_POST['subject'];
$message = $_POST['mailbody'];
// Temporary paths of selected files
$file1 = $_FILES['file1']['tmp_name'];
$file2 = $_FILES['file2']['tmp_name'];
$file3 = $_FILES['file3']['tmp_name'];
// File names of selected files
$filename1 = $_FILES['file1']['name'];
$filename2 = $_FILES['file2']['name'];
$filename3 = $_FILES['file3']['name'];
// array of filenames to be as attachments
$files = array($file1, $file2, $file3);
$filenames = array($filename1, $filename2, $filename3);
// include the from email in the headers
$headers = "From: $from";
// boundary
$time = md5(time());
$boundary = "==Multipart_Boundary_x{$time}x";
// headers used for send attachment with email
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$boundary}\"";
// multipart boundary
$message = "--{$boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$boundary}\n";
// attach the attachments to the message
for($x = 0; $x < count($files); $x++){
if($files[$x] != ""){
$file = fopen($files[$x],"r");
$content = fread($file,filesize($files[$x]));
fclose($file);
$content = chunk_split(base64_encode($content));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . "Content-Disposition: attachment;\n" . " filename=\"$filenames[$x]\"\n" . "Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$boundary}\n";
}
}
// sending mail
$sendmail = mail($to, $subject, $message, $headers);
As I understand it, Outlook creates ATT12345.txt attachments when it receives messages in sections with mixed encoding. If it is unable to convert the remainder of the message after a change in encoding (or new MIME part), it dumps the rest in an attachment with the generic names you have been seeing. It seems as if Gmail is handling the format better than Outlook (unsurprising).
I am no Outlook expert (never touch the thing), but it looks as if this answer on SO might help (check your $mime_boundary variable for a trailling '--' after the last part).