mail function does not echo value in email - php

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';
}
}

Related

loosing part of image during mail delivery

I've got a problem sending email with php. The first line of my base64 encoded image disappears during mail delivery. What am I doing wrong here?
This is part of the printed message before sending:
...
--67e5a910fa8cffc2b52b2aec743f9332
Content-Disposition: attachment
Content-Type: image/svg; name="aaa.svg"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="aaa.svg"
PHN2ZyB2aWV3Qm94PSIwIDAgMjk2NjkgMjA5OTAiIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcv
ZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25z
...
This is the message i receive:
...
--67e5a910fa8cffc2b52b2aec743f9332
Content-Disposition: attachment
Content-Type: image/svg; name="aaa.svg"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="aaa.svg"
ZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25z
...
my code:
<?php
if($_POST) {
date_default_timezone_set('Europe/Berlin');
$uid = md5(uniqid(time()));
$eol = PHP_EOL;
$name = $_POST['name'];
$gliderName = $_POST['glider'];
$gliderSize = $_POST['size'];
$subject = $gliderName . "_" . $gliderSize . "_" . $name . "_" . date('d-m-Y_h:i:s', time());
$subject = str_replace(' ', '_', $subject);
$comment = $_POST['comment'];
$attachment = $_POST['image'];
$sendToSwing = $_POST['sendToSwing'];
$mail = $_POST['email'];
$mail_to = $mail;
if ($sendToSwing) {
$mail_to .= "," . "ZIELADRESSE#aaa.DE";
}
$mail_from = "ABSENDERADRESSE#aaa.DE";
$from_name = "ABSENDERNAME";
$header = "From: " . $from_name . " <" . $mail_from . ">" . $eol;
$header .= "Reply-To: " . $mail_from.$eol;
$header .= "MIME-Version: 1.0" . $eol;
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"" . $eol . $eol;
$msg = '<html><head><title>' . $subject . '</title></head><body>' . $eol;
$msg .= '<b>glider:</b> ' . $gliderName . $eol;
$msg .= '<b>size:</b> ' . $gliderSize . $eol;
$msg .= '<b>customer name:</b> ' . $name . $eol;
$msg .= '<b>customer email:</b> ' . $mail . $eol;
$msg .= '<b>message from customer:</b> ' . $comment . $eol;
$msg .= '</body></html>' . $eol;
$message = "--" . $uid . $eol;
$message .= "Content-type:text/html; charset=utf-8" . $eol;
$message .= "Content-Transfer-Encoding: utf-8" . $eol . $eol;
$message .= $msg . $eol;
// attachment
//echo $eol.$attachment.$eol;
$attachment = chunk_split(base64_encode($attachment));
//echo $eol.$attachment.$eol;
$message .= "--" . $uid . $eol;
$message .= "Content-Type: image/svg; name=\"" . $subject . ".svg\"" . $eol;
$message .= "Content-Transfer-Encoding: base64" .$eol;
$message .= "Content-Disposition: attachment; filename=\"" . $subject . ".svg\"" . $eol;
$message .= $attachment . $eol;
$message .= "--".$uid."--";
echo $eol.$message.$eol;
if (mail($mail_to, $subject, $message, $header)) {
echo "success ";
} else {
echo "error sending email";
}
}
?>
Like this it should work (two new line before the payload):
$message .= "Content-Disposition: attachment; filename=\"" . $subject . ".svg\"" . $eol.$eol;

PHP Header not redirecting from Form Submit action page

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');

Images not sent to inbox, using PHP mail()

I have an online property submission area in my website which lets users send properties in the form of text with images, to my email address:
But I'm not receiving the images. I only receive the text. I am trying to figure out why this is happening, but I couldn't find out anything that would cause this. Can someone help me find out the issue?
Code:
<?php
if (isset($_POST['propertystatus'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "contact#scale-property.com";
$email_subject = "New Property From Customer";
$email_subject_to_user = "Copy of your email";
$propery_Information = 'PROPERTY INFORMATION';
$propery_Location = 'PROPERTY LOCATION';
$contact_Information = 'CONTACT INFORMATION';
function died($error)
{
// your error code can go here
echo "We are very sorry, but there were errors found with the form you submitted.<br>";
echo $error . "<br />";
die();
}
// validation expected data exists
if (!isset($_POST['propertystatus']) || !isset($_POST['currencytype']) || !isset($_POST['currency']) || !isset($_POST['rooms']) || !isset($_POST['bathroom']) || !isset($_POST['kitchen']) || !isset($_POST['yard']) || !isset($_POST['housedesproperty']) || !isset($_POST['drop_1']) || !isset($_POST['drop_2']) || !isset($_POST['drop_3']) || !isset($_POST['region']) || !isset($_POST['street']) || !isset($_POST['name']) || !isset($_POST['emailadd']) || !isset($_POST['conemailadd']) || !isset($_POST['phone1']) || !isset($_POST['phone2']) || !isset($_FILES['uploadimages'])) {
died('You have not properly selected the fields.');
}
// start code of attachement
if (empty($_FILES['uploadimages']['name'])) {
echo 'You have\'nt Entered Value for upload field';
exit();
} else {
$attachment = $_FILES['uploadimages']['tmp_name'];
$attachment_name = $_FILES['uploadimages']['name'];
if (is_uploaded_file($attachment)) {
$fp = fopen($attachment, "rb");
$data = fread($fp, filesize($attachment));
$data = chunk_split(base64_encode($data));
fclose($fp);
}
$headers = "From: $email<$email>\n";
$headers .= "Reply-To: <$email>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
$headers .= "X-Mailer: PHP4\n";
$headers .= "X-Priority: 3\n";
$headers .= "Return-Path: <$email>\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "------=MIME_BOUNDRY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";
$message = "------=MIME_BOUNDRY_message_parts\n";
$message .= "Content-Type: text/html; charset=\"utf-8\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";
$message .= "------=MIME_BOUNDRY_message_parts--\n";
$message .= "\n";
$message .= "------=MIME_BOUNDRY_main_message\n";
$message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n";
$message .= $data; //The base64 encoded message
$message .= "\n";
$message .= "------=MIME_BOUNDRY_main_message--\n";
mail($email_to, $email_subject, $message, $headers);
}
// end code of attachment
$property_status = $_POST['propertystatus']; // required
$currency_type = $_POST['currencytype']; // required
$currency = $_POST['currency']; // required
$rooms = $_POST['rooms']; // required
$bathroom = $_POST['bathroom']; // required
$kitchen = $_POST['kitchen']; // required
$yard = $_POST['yard']; // required
$housedesproperty = $_POST['housedesproperty']; // required
$drop_1 = $_POST['drop_1']; // required
$drop_2 = $_POST['drop_2']; // required
$drop_3 = $_POST['drop_3']; // required
$region = $_POST['region']; // required
$street = $_POST['street']; // required
$name = $_POST['name']; // required
$emailadd = $_POST['emailadd']; // required
$conemailadd = $_POST['conemailadd']; // required
$phone1 = $_POST['phone1']; // required
$phone2 = $_POST['phone2']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp, $emailadd) && !preg_match($email_exp, $conemailadd)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$email_message = "Property details below.\n\n";
function clean_string($string)
{
$bad = array(
"content-type",
"bcc:",
"to:",
"cc:",
"href"
);
return str_replace($bad, "", $string);
}
$email_message .= "" . clean_string($propery_Information) . "\n";
$email_message .= "--------------------------------------------" . "\n";
$email_message .= "Property Status: " . clean_string($property_status) . "\n";
$email_message .= "Total Price: " . clean_string($currency_type) . " " . (number_format($currency, 2, '.', ',')) . "\n";
$email_message .= "Rooms: " . clean_string($rooms) . "\n";
$email_message .= "Bathrooms: " . clean_string($bathroom) . "\n";
$email_message .= "Bathrooms: " . clean_string($kitchen) . "\n";
$email_message .= "Bathrooms: " . clean_string($yard) . "\n";
$email_message .= "Description: " . clean_string($housedesproperty) . "\n\n";
$email_message .= "" . clean_string($propery_Location) . "\n";
$email_message .= "--------------------------------------------" . "\n";
$email_message .= "Province: " . clean_string($drop_1) . "\n";
$email_message .= "District: " . clean_string($drop_2) . "\n";
$email_message .= "PD(Nahya): " . clean_string($drop_3) . "\n";
$email_message .= "Bathrooms: " . clean_string($region) . "\n";
$email_message .= "Street: " . clean_string($street) . "\n\n";
$email_message .= "" . clean_string($contact_Information) . "\n";
$email_message .= "--------------------------------------------" . "\n";
$email_message .= "Name: " . clean_string($name) . "\n";
$email_message .= "Email ID: " . clean_string($emailadd) . "\n";
$email_message .= "Con-Email ID: " . clean_string($conemailadd) . "\n";
$email_message .= "Phone(1): " . clean_string($phone1) . "\n";
$email_message .= "Phone(2): " . clean_string($phone2) . "\n";
// create email headers
$headers = 'From: ' . $emailadd . "\r\n" . 'Reply-To: ' . $emailadd . "\r\n" . 'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
#mail($emailadd, $email_subject_to_user, $email_message, "From: $email_to");
?>
<!-- include your own success html here -->
Your Property has been Posted please check your email address.
<?php
}
?>
Try this,this for multiple image attachment
http://www.emanueleferonato.com/2008/07/22/sending-email-with-multiple-attachments-with-php/

Uploading File via PHP shredding .xls files

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 .= '--';

How to send email attachments in PHP

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

Categories