How to send email attachments in PHP - 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).

Related

How to send email with not necessary Multiple Attachments from html form in PHP

I have get value from html form and send via email with multiple attachments. Attachments are not necessary.
I have got some piece of code to send multiple attachments through mail function in php But my mail sending fails and i dont know why. My attachments are not necessary. This is my code:
<?php
function multi_attach_mail($to, $subject, $message, $senderMail, $senderName, $files){
$from = $senderName." <".$senderMail.">";
$headers = "Siuntėjęs: $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 = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"utf-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
if(count($files) > 0){
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $senderMail;
//send email
$mail = #mail($to, $subject, $message, $headers, $returnpath);
//function return true, if email sent, otherwise return fasle
if($mail){ return TRUE; } else { return FALSE; }
}
if($_SERVER['REQUEST_METHOD'] == 'POST'
&& !empty($_POST['namecontact'])
&& !empty($_POST['namecarinfo']) ) {
$contacts = array(
//"autoperka.info#gmail.com",
//"automobiliukas24#gmail.com",
// "ruslanneviadomskij#gmail.com",
"gabriele.giniot#gmail.com"
);
foreach($contacts as $contact) {
$to = $contact; // this is your Email address
$from = $_POST['namecontact']; // this is the sender's Email address
$carinformation = $_POST['namecarinfo'];
$coment = $_POST['namecoment'];
$subject = $from . " SupirkimasPlius.lt";
$from_name = $_POST['namecontact'];
//$headers = "Siuntėjas:" . $from;
//attachment files path array
$file_tmp_name = $_FILES['namephoto']['tmp_name'];
$fileName = $_FILES['namephoto']['name'];
$fileType = $_FILES['namephoto']['type'];
$files = $fileType;
// Message
$html_content = '<br>
<h3>Automobilio pasiūlymas:</h3>
<br>Marke: '.$carinformation.'
<br>Kontaktai: '.$from.'
<br>Komentaras: '.$coment.
'<br>Nuotraukų kiekis'.count($files);
//call multi_attach_mail() function and pass the required arguments
$send_email = multi_attach_mail($to,$subject,$html_content,$from,$from_name,$files);
//print message after email sent
}
$myfile = fopen("success.php", "r") or die(fopen("index.php", "r"));
echo fread($myfile,filesize("success.php"));
fclose($myfile);
//mail('gabriele.giniot#gmail.com',$subject,$message,$headers);
//mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
} else {
$myfile = fopen("failed.php", "r") or die(fopen("index.php", "r"));
echo fread($myfile,filesize("failed.php"));
fclose($myfile);
}
?>
please help me :)

Mail Server Spam Security Issue

I'm getting spam emails from my web form every week. I have tried to make some changes in my query, but that hasn't helped. I am sharing my query below, including the headers.
Can someone help me find where the problem is?
<?php
$submitted_email = '';
if (isset($_SESSION['form'][$mail_from_email])) {
$submitted_email = $_SESSION['form'][$mail_from_email];
}
if (check_email($submitted_email) && $send_from_users_email === false) {
$from = $reply_to = $_SESSION['form'][$mail_from_name].' <'.$submitted_email.'>';
} else {
$from = '<'.$email.'>';
$reply_to = check_email($submitted_email) ? '<'.$submitted_email.'>' : $from;
}
$subject = '';
if (isset($_SESSION['form'][$mail_subject])) {
$subject = $_SESSION['form'][$mail_subject];
}
//email headers
if ($windows_server === true) {
$headers = "From: test.co.uk\r\n" .
"Reply-to: test.co.uk\r\n" .
"Return-Path: test.co.uk\r\n".
"MIME-Version: 1.0\r\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
} else {
$headers = "From: $from\n" .
"Reply-to: $reply_to\n" .
"MIME-Version: 1.0\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
} else {
$headers = "From: $from\n" .
"Reply-to: $reply_to\n" .
"MIME-Version: 1.0\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
}
////////////////////////////
// CONSTRUCT HTML CONTENT //
////////////////////////////
//Construct HTML email content, looping through each form element
//Note: When you get to a file attachment you need to use $_FILES['form_element']['name']
//This will just output the name of the file. The files will actually be attached at the end of the message.
//Set a variable for the message content
$html_content = "<html>\n<head>\n<title>" .
safe_escape_string($subject) .
"</title>\n</head>\n<body>\n<p>\n";
////////////////////////////
// CONSTRUCT TEXT CONTENT //
////////////////////////////
//construct a plain text version of the email.
$text_content = '';
//build a message from the reply for both HTML and text in one loop.
foreach ($form_fields as $field => $label) {
$html_content .= '<b>' . safe_escape_string($label) . '</b> ';
$text_content .= "$label ";
if (isset($_FILES[$field])) {
$string = (isset($_FILES[$field]['name'])) ? $_FILES[$field]['name'] : '';
} else {
$string = (isset($_SESSION['form'][$field])) ? $_SESSION['form'][$field] : '';
}
$html_content .= nl2br(safe_escape_string($string)) . "<br /><br />\n";
$text_content .= "$string\n\n";
}
//close the HTML content.
$html_content .= "</p>\n</body>\n</html>";
/////////////////////////////
// CONSTRUCT EMAIL MESSAGE //
/////////////////////////////
//Now we combine both HTML and plain text version of the email into one.
//Creating the message body which contains a Plain text version and an HTML version,
//users email client will decide which version to display
$message = "\r\n--$mixed_mime_boundary\r\n" .
"Content-Type: multipart/alternative; boundary=$alt_mime_boundary\r\n\r\n" .
"--$alt_mime_boundary\r\n" .
"Content-Type: text/plain; charset=UTF-8; format=flowed\r\n" .
"Content-Transfer-Encoding: Quoted-printable\r\n\r\n" .
"$text_content\r\n\r\n" .
"--$alt_mime_boundary\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n" .
"Content-Transfer-Encoding: Quoted-printable\r\n\r\n" .
"$html_content\r\n\r\n" .
"--$alt_mime_boundary--\r\n\r\n" .
"\r\n\r\n--$mixed_mime_boundary";
//////////////////////
// FILE ATTACHMENTS //
//////////////////////
//loop through the $_FILES global array and add each attachment to the form.
if (isset($_FILES)) {
foreach ($_FILES as $attachment) {
$filename = $attachment['name'];
//if the file has been uploaded
if ($attachment['error'] === UPLOAD_ERR_OK && is_uploaded_file($attachment['tmp_name'])) {
$file = fopen($attachment['tmp_name'],'rb');
$data = fread($file,filesize($attachment['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "\r\nContent-Type: application/octet-stream; name=\"$filename\"" .
"\r\nContent-Disposition: attachment; filename=\"$filename\"" .
"\r\nContent-Transfer-Encoding: base64\r\n\r\n$data\r\n\r\n--$mixed_mime_boundary";
} else if ($attachment['error'] !== UPLOAD_ERR_NO_FILE) {
//try to provide a useful error message determined from the error code.
switch ($attachment['error']) {
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$error = "File $filename exceeds the " . ini_get('upload_max_filesize') . 'B limit for the server.';
break;
case UPLOAD_ERR_PARTIAL:
$error = "Only part of the file $filename could be uploaded, please try again.";
break;
default:
$error = "There has been an error attaching the file $filename, please try again.";
}
redirect($return_url, $error);
}
}
}
//finish off message
$message .= '--';
//for windows users.
if ($windows_server === true) {
ini_set('sendmail_from', $email);
}
//if the mail sending works
if (#mail($email, $subject, $message, $headers)) {
//set the success message
$notice = $message_success;
unset($_SESSION['form']);
} else {
$notice = "I'm sorry, there seems to have been an error trying to send your email. Please try again.";
}
//redirect to the form
redirect($return_url, $notice);
}
?>

mail function does not echo value in email

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

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.

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

Categories