I'm trying to send an attachment via email but, even though the right file is saved in the server, the one attached to the email is empty (0 kb).
I'm using gmail to send the emails.
Here is the relevant part of my code:
if (empty($error)) {
//boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x$semi_randx";
//tell the headers about the boundary
$header .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"$mime_boundary\"";
//define the first part of the email, which is the text part
$message = "\r\n" . "--$mime_boundary\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\r\n" ;
//build the body of the 1st part of the email
$content_body = "
Email del formulario de contacto en ".home_url().": <br />
//whatever
";
$message .= $content_body . "\r\n";
$message .= "--$mime_boundary\n";
//define the second part of the email, which is the atachments
//if a file has been uploaded
if (!empty($_FILES['cv']['name'])){
// Open the file for a binary read
$file = fopen($temp_name,'rb');
// Read the file content into a variable
$data = fread($file,filesize($temp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
// Actually build the second part of the email
$message .= "Content-Type: \"application/octet-stream\";\r\n name=\"" . $file_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\r\n filename=\"" . $file . "\"\r\n\r\n";
$message .= $data; //The base64 encoded message
$message .= "\n";
$message .= "--$mime_boundary--\n";
}
//send th email
mail( $receive_email, "Email del formulario de contacto en web", $message, $header);
$msg = $succesful_text;
}
My guess is that I'm doing something wrong here:
$message .= "Content-Type: \"application/octet-stream\";\r\n name=\"" . $file_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\r\n filename=\"" . $file . "\"\r\n\r\n";
$message .= $data; //The base64 encoded message
$message .= "\n";
$message .= "--$mime_boundary--\n";
But I have no idea what it can be.
I know I can use a library, but I would like to see what is wrong with my code just for the sake of learning.
Any help will be highly appreciated.
Sonia
Thanks Cherry and miken32 for your replies.
Finally I figured it out.
This is what happened, in case it can help somebody else in a future.
As there was no base64 encoded data in the text message, I thought the problem might no be in the $message text but in the actual handling of the file.
// Open the file for a binary read
$file = fopen($temp_name,'rb');
// Read the file content into a variable
$data = fread($file,filesize($temp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
I realized the temp file was not being opened. I couldn't see why but I solved it by handling directly the file from the uploads folder.
Here is the fixed code:
// Open the file for a binary read
$file = fopen($server_file,'rb');
// Read the file content into a variable
$flsz=filesize($server_file);
$data = fread($file,$flsz);
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
I also had to modify the filename in the $message text, using $file_name instead of $file because $file.
$message .= "Content-Disposition: attachment;\r\n filename=\"" . $file_name . "\"\r\n\r\n";
Related
I am a complete novice with php, so forgive me if this is something very obvious! I have tried to create an html form on my website which, when submitted, generates an email with a csv attachement which is sent to me with the relevant information.
I have been using code found online (some from this forum) to try to create a solution and seem to be vey close - however there is a problem somewhere. I am receiving 2 emails when submitted - the first is incorrect in that it is missing the senders' email address and the csv has no information - the second email is exactly right however.
This is the code I am using:
<?php
$email=$_POST['email'];
$customer=$_POST['customer'];
$quantity=$_POST['quantity'];
$prefix=$_POST['prefix'];
$itemno=$_POST['itemno'];
$format=$_POST['format'];
$to = "me#myemail.com";
$subject = "Form 01";
//Message Body
$text = "Form 01 attached";
//The Attachment
$cr = "\n";
$data .= "$email" . $cr;
$data .= "$customer" . $cr;
$data .= "$quantity" . $cr;
$data .= "$prefix" . $cr;
$data .= "$itemno" . $cr;
$data .= "$format" . $cr;
$fp = fopen('form01.csv','a');
fwrite($fp,$data);
fclose($fp);
$attachments[] = Array(
'data' => $data,
'name' => 'form_01.csv',
'type' => 'application/vnd.ms-excel'
);
//Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//Add the headers for a file attachment
$headers = "MIME-Version: 1.0\n" .
"From: {$from}\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
//Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$text . "\n\n";
//Add attachments
foreach($attachments as $attachment){
$data = chunk_split(base64_encode($attachment['data']));
$name = $attachment['name'];
$type = $attachment['type'];
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" ;
}
$message .= "--{$mime_boundary}--\n";
mail($to, $subject, $message, $headers);
?>
I am also trying to add in reCaptcha, this is going in fine except it only seems to be allowing the first email to get through - which is the incorrect one. So I hope if the problem is in the code above and it can be fixed, then this should be solved too.
Thanks in advance!
The code you are giving us is (I guess) incomplete. It is (obviously) not the complete HTML page. I guess this PHP script is at the top of your HTML page right above your form. Am I right?
So when you open the page your PHP script sends the first (empty) email. After the form is submitted and your $_POST array is filed with data the second (and correct) email will be sent.
To fix this you must check if the $_POST array is not empty:
<?php
if (!empty($_POST["email"])) {
//your code here
}
?>
Like this here: If isset $_POST
I am trying to attach two files at maximum, to send them by mail, but the files are sent by mail as binary code, so when I open the received mail I found the files as binary, here is my code:
$files = array();
if(is_uploaded_file($_FILES['cv']['tmp_name']))
array_push($files, $_FILES['cv']);
if(is_uploaded_file($_FILES['portfolio']['tmp_name']))
array_push($files, $_FILES['portfolio']);
$subject = "Contact Mail";
$headers = 'From: '.$email_fromto."\r\n".
"subject: {$subject}";
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
"From: $sex $fname $lname.\r\n".
"Message: {$message}";
$email_fromto = "mail#mail.com";
foreach($files as $userfile){
$tmpName = $userfile['tmp_name'];
$fileType = $userfile['type'];
$fileName = $userfile['name'];
if(file($tmpName)){
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
}
so where is the error in what I did?
use like this
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// here, we'll start the message body.
// this is the text that will be displayed
// in the e-mail
$message="This is an example"
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
}
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content.
// NOTE: we don't set another boundary to indicate that the end of the
// file has been reached here. we only want one boundary between each file
// we'll add the final one after the loop finishes.
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
// here's our closing mime boundary that indicates the last of the message
$message.="--{$mime_boundary}--\n";
// now we just send the message
if (#mail($to, $subject, $message, $headers))
echo "Mail was Send Sucessfully";
else
echo "Failed to send";
Just to be clear - I didn't write this code, this is from a previous developer.
Anyway, my client isn't receiving images when uploaded via their form, just a red box with an error message.
As per request here is the whole code:
<?php
function sendMail() {
if (!isset ($_POST['to_email'])) { //Oops, forgot your email addy!
die ("<p>Oops! You forgot to fill out the email address! Click on the back arrow to go back</p>");
}
else {
$to_name = stripslashes($_POST['to_name']);
$from_name = stripslashes($_POST['from_name']);
$from_telephone = stripslashes($_POST['from_telephone']);
$subject = stripslashes($_POST['subject']);
$body = stripslashes($_POST['body']);
$address = stripslashes($_POST['address']);
$to_email = $_POST['to_email'];
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
//Let's start our headers
$headers = "From: $from_name<" . $_POST['from_email'] . ">\n";
$headers .= "Reply-To: <" . $_POST['from_email'] . ">\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
$headers .= "X-Sender: $from_name<" . $_POST['from_email'] . ">\n";
$headers .= "X-Mailer: PHP4\n";
$headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . $_POST['from_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/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= "Return call on: $from_telephone\n\n";
$message .= "$address\n\n";
$message .= "$body\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";
// send the message
mail("$to_name<$to_email>", $subject, $message, $headers);
print "<p align=\"center\">Thank you for your email.</p>";
}
}
switch ($action) {
case "send":
showForm();
sendMail();
break;
default:
showForm();
}
?>
I'm completely confused by this code as I didn't write it and can't decrypt why "$attachment" and "$attachment_name" are separate strings, if I change the "attachment_name" to "attachment" will my problems be fixed?
The code that you have seems to work for me, but there are a few potential problems. I think perhaps the most important one is that the image is sent using an incorrect Content-Type:, but there are also some other issues detailed below.
Image type
$message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n";
The application/octet-stream is used as a last resort for sending arbitrary binary data when there is no appropriate content type, or the content type is unknown. You should use a proper image type:
$message .= "Content-Type: " . $_FILES['attachement']['type']
. ";\n\tname=\"" . $attachment_name . "\"\n";
If you want to prevent users from mailing arbitrary files, you can use a white-list:
if (is_uploaded_file($attachment) &&
in_array ($attachment_type, array ('image/gif', 'image/png', 'image/jpg', 'image/jpeg'))) {
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose ($fp);
} else {
echo "<p>Useful error message\n";
exit;
}
MIME syntax
$headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . $_POST['from_email'] . ">\n";
$headers .= "This is a multi-part message in MIME format.\n";
The Return-Path: is the last of your headers. The next line is part of the message body. You need a blank line to separate the message body from the headers. Eg:
$headers .= "Return-Path: <" . $_POST['from_email'] . ">\n";
$headers .= "\n";
$headers .= "This is a multi-part message in MIME format.\n";
Personally, I would add the message body to $message instead. The mail() function doesn't care, it just concatenates the headers and message with a line break. See more about line endings below.
$headers .= "------=MIME_BOUNDRY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";
$message = "------=MIME_BOUNDRY_message_parts\n";
Note that if you do move some of the lines above to $message, you need to insert an extra line break after the Content-Type: header.
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
...
$message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n";
$attachment_name is sent by the browser and is typically the original name of the file uploaded by the user. $attachment is the name of the temporary file where the image is stored on the server. The two are entirely different and are not interchangeable.
You may want to strip control characters (such as line breaks) and double quotes from these variables to prevent malicious users from disrupting the syntax of the headers.
Line endings
According to the Mail syntax, lines should be terminated with a CRLF("\r\n") sequence, but it is not clear which line ending should be used when calling the mail() function. The PHP documentation says:
If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.
$_POST[] data
You should not use raw data from $_POST[] in your mail headers. A malicious user could easily insert their own headers (such as Bcc:) to send spam to arbitrary addresses. You should at least filter out control characters (such as line breaks) and perhaps also filter or escape angle brackets and double quotes depending on usage.
I have extracted data from my database and displayed it on a webpage in table format. I provided a link on this page which allows the user to download this data as a CSV file. This works correctly so far and when the user follows the link beneath the displayed data it allows them to save it.
It also sends an email with the CSV as an attachment. However currectly the CSV in the attachment is blank and I dont know why.
All i want is for the data from the database which is placed into a downloadable CSV to also go into the attached CSV and I cant do it.
Could someone help me?
Here is the code I have so far:
// Create CSV file
fputcsv($output, array('Name', 'Branch', 'Website','Company', 'Question1', 'Question2', 'Question3', 'Question4', 'Question5'));
$mysql_connection = db_connect_enhanced('*******','******','******','******');
$query='SELECT * FROM ****.****';
$surveys = db_query_into_array_enhanced($mysql_connection, $query);
$count = count($surveys);
$data = array();
for($i=0; $i<=$count; $i++){
$data[] = array($surveys[$i]['FeedbackName'], $surveys[$i]['BranchName'], $surveys[$i]['FeedbackWebsite'], $surveys[$i]['FeedbackCompany'], $surveys[$i]['Question1'], $surveys[$i]['Question2'], $surveys[$i]['Question3'], $surveys[$i]['Question4'], $surveys[$i]['Question5']);
}
foreach( $data as $row )
{
fputcsv($output, $row, ',', '"');
}
$encoded = chunk_split(base64_encode($data));
// create the email and send it off
$subject = "File you requested from RRWH.com";
$from = "***************";
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-Type: multipart/mixed;
boundary="----=_NextPart_001_0011_1234ABCD.4321FDAC"' . "\n";
$message = '
This is a multi-part message in MIME format.
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
Hello
We have attached for you the PHP script that you requested from http://rrwh.com/scripts.php
as a zip file.
Regards
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: application/octet-stream; name="';
$message .= "surveys.csv";
$message .= '"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="';
$message .= "surveys.csv";
$message .= '"
';
$message .= "$encoded";
$message .= '
------=_NextPart_001_0011_1234ABCD.4321FDAC--
';
mail("*************", $subject, $message, $headers, "-f$from");
fclose($output);
It feels like I am so close but I just cant see the answer :(
Change this line:
$message .= "$encoded";
With this one:
$message .= $encoded;
This is only a "SUGGESTIVE" answer:
Here is what I use to attach files and it works for me and it may help you to "BASE" yourself with the problem you're having.
$file_path = "/path_to_your/$file_name";
$file_path_name = "$file_name"; // this file name will be used at receiver end
$file = fopen($file_path,'rb');
$data = fread($file,filesize($file_path));
fclose($file);
$rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$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/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message .= "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$file_path_type};\n" .
" name=\"{$file_path_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$file_path_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data .= "\n\n" .
"--{$mime_boundary}--\n";
I am trying to send a CSV file as an attachment in PHP and using mail function for attachments. The following code works fine. It successfully attaches the CSV file and sends it to the recipient but the ATTACHED output file (sent in email) comes in text format(.txt). I don't know where i am making mistake and what i need to change in header to retain original CSV file format in attached email.
$path ="/myhost/public_html/csv/";
$file_name = $path."Test";
$file_name.=".csv";
$from = "some#myemail.co.uk";
$to = "other#hisemail.co.uk";
$fat=$file_name;
$subject = $_POST[subject];
// $message = $_POST[message];
//replace \n with <br>
$message = str_replace("\n", "<br>",$message);
//report
echo "<b><font color=#8080FF> From: $from </b><br>";
echo "<b>To: $to </b><br>";
echo "<b>Subject: $subject</b><br><br></font>";
// Obtain file upload variables
$fileatt = $_FILES[$fat]['tmp_name'];
$fileatt_type = $_FILES[$fat]['type'];
$fileatt_name = $_FILES[$fat]['name'];
$headers = "From: $from \n";
// if($_FILES['fileatt']['size'] > 0)
if (file_exists($fat)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fat,'rb');
$data = fread($file,filesize($fat));
fclose($file);
// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers .= "MIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the message
$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";
// Base64 encode the file data
$data = chunk_split(base64_encode($data));
// Add file attachment to the message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
} else echo "File error! ";
//send the mail
if(mail($to, $subject, $message,$headers))echo "<b><font color=#FF0000>Message was sent!<b></font>";
else echo "<b><font color=#FF0000>Message error!<b></font>";
I just want to retain original file format in email attachments. Help me please.
I would recommend using a library to handle email attachments. This kind of thing can get complicated quickly and someone else out there has already figured out all the ins and outs of what needs to happen when CSV files are attached. I would use something like http://swiftmailer.org/
You could do all of the code you have above, or something more like...
require_once 'lib/swift_required.php';
$message = Swift_Message::newInstance()
->setSubject('Your subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
->addPart('<q>Here is the message itself</q>', 'text/html')
->attach(Swift_Attachment::fromPath('my-document.csv'));
Example from: http://swiftmailer.org/docs/messages.html
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
this might be helpful ?