CSV attachment in PHP - php

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 ?

Related

mail() can't send attachment title with utf-8. English titled attachment passes with utf-8 content

When I send file with eg. title: zażółć gęślą jaźń.pdf it don't pass(I dont get any email) but when i send eg. toSend.pdf all works. Both attachment contain "zażółć gęślą jaźń" and email body have no problem with utf-8
I'm trying to pass file by POST( ) and process it in php to make email attachment form it.
$toEmail = 'myEmail#myDomain';
$from = 'email#realDomain';
$fromName = 'Formularz kariera';
// Subject
$emailSubject = 'CV dla '.$wybor;
// Message
$htmlContent = '<h3> importantcontent zażółć gęślą jaźń</h3>';
$headers = "From: ".$fromName." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// 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" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$mail = mail($toEmail, '=?utf-8?B?'.base64_encode($emailSubject).'?=', $message, $headers, /*$returnpath,*/ "-f email#realDomain");
// Delete attachment file from the server
#unlink($uploadedFile);
I dug through the internet in search of a solution but I have found none. I hope that's becouse Im noob in php
Code is good(enought) and problem was POSTFIX's SMTPUTF8 enabled on server ...
to fix i just.
postconf "smtputf8_enable = no"
AVE server logs!

Generate PDF and sent it through Email as Attachment (PDF is not opening)

I am generating pdf and sent it through email as attachment the code is given below for this i skipped some code for generating pdf (not needed).
Please check the code:
//pdf generated not given avobe code of how it comes
$pdfdoc = $pdf->Output("confirmation-".$client_code.".pdf", "S");
$attachment = chunk_split(base64_encode($pdfdoc));
$to = $mail_to;
$from = "From: <info#ksilbd.com>";
$subject = "Here is your attachment";
$mainMessage = "BUY/SALE CONFIRMATION";
$fileatt = $attachment;
$fileatttype = "application/pdf";
$fileattname = "confirmation-".$client_code.".pdf";
$headers = "From: $from";
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
$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" .
$mainMessage . "\n\n";
//base_64
//encoding used
//to encode data
$data = chunk_split(base64_encode($data));
//message
//concat the
//message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "EMAIL SENT SUCCESSFUL.";
}
else {
echo "There was an error sending the mail.";
The message showed email sent successful and i got email too but i failed to open the attached pdf file with the mail ....
please check the problem
You may use "phpmailer".
Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer
and Enjoy it.

Attach pdf to e-mail. Message doesn't work

This php script works just fine sending my pdf file by e-mail.
The problem is the script doesn't send any message as specified in $mainMessage.
Why do that problem occur, with the script only sending the pdf file without any message?
// Settings
$name = "Name";
$email = "someome#anadress.com";
$to = "$name <$email>";
$from = "email#email.com";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt = "test.pdf";
$fileatttype = "application/pdf";
$fileattname = "newname.pdf";
$headers = "From: $from";
// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
// This attaches the file
$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" .
$mainMessage . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
Try using \r\n instead of your \ns. Also, I would suggest using a library for sending emails, such as PHPMailer or SwiftMailer, instead.
EDIT: There appears to be an extra (or missing) " when you declare your charset (at "Content-Type: text/plain; charset=\"iso-8859-1\n" - it outputs Content-Type: text/plain; charset="iso-8859-1).
you didn't notice that you need to complete this line:
$message = "This is a multi-part message in MIME format.\r\n" .
"--{$mime_boundary}\r\n" .
"Content-Type: text/plain; charset=utf-8 \r\n" .
"Content-Transfer-Encoding: 7bit\r\n" .
$mainMessage . "\r\n\r\n";
you are missing one "-" in "-{$mime_boundary}\r\n".
it should be as the example I wrote :3

Sending multiple Attachment files in php mail function

I have got some piece of code to send multiple attachments through mail function in php.
The mail with attachment will be sent if there is only one attachment.
But mail sending fails if add two or more files in the array.
This is my code
// array with filenames to be sent as attachment
//$files = array("upload/Tulip.jpg");
$files = array("upload/Tulip.jpg","upload/Tulips.jpg","upload/Tulips1.jpg");
// email fields: to, from, subject, and so on
$to = "mail#mail.com";
$from = "mail#mail.com";
$subject ="My subject";
$message = "My message";
$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";
}
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
The mail will be sent if $files array have only one file..
Please someone help me in solving this.
Please Remember , the above code works fine if we have only one image path in $files array.
Thanks in advance

Attach file from the server into email

can anyone give me some idea how to attach a file from the server and send it as attachment through email??
i have the following code:
<?php
// Read POST request params into global vars
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Obtain file upload vars
$fileatt = $_FILES['fileatt']['tmp_name'];
$fileatt_type = $_FILES['fileatt']['type'];
$fileatt_name = $_FILES['fileatt']['name'];
$headers = "From: $from";
if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
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 .= "\nMIME-Version: 1.0\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/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// Base64 encode the file 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";
}
// Send the message
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>Mail sent! Yay PHP!</p>";
} else {
echo "<p>Mail could not be sent. Sorry!</p>";
}
?>
but this code does not attach file from the server.
please help me out.. thanks in advance..!!
One question: Do you want to send e-mails with attachment or do you want to improve your PHP skills with this problem?
If you only want to send mails, have a look at PHPMailer which is very good and easily to handle. For myself I'm using this for years without problems.
For improving your skills: You say that the attachment is encoded in base64, but I cannot find the line where you do something like $data = base64_encode($data); You add the $data of your attachment in plain to the mail.

Categories