Creating excel report with php and sending by email - php

I have this php that generates an excel file for me with php reading from a database. I would like to be able to email the excel (as an attachment). The problem is that I can only get the file download but when I get the email there is no attachment
Could you help me?
When the email arrives I have only this result, without any attachment (excel file):
--90215ae30d47b3d98d4505ee5035e618
Content-Transfer-Encoding: 7bit
This is a MIME encoded message.
--90215ae30d47b3d98d4505ee5035e618
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 8bit
--90215ae30d47b3d98d4505ee5035e618
Content-Type: application/octet-stream; name="test.xls"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="test.xls"
MQkwMzAyMDE4NTIzCU1HTkdQUDg0QTE4QzM1MVcJTUFHTkFOTyBESSBTQU4gTElPICAgICAgICAg
ICAgICAgICAgICAgIAlHSVVTRVBQRSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCQ==
--90215ae30d47b3d98d4505ee5035e618--
<?php
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=test.xls");
header("Pragma: no-cache");
header("Expires: 0");
$db2 = db2_connect();
$sep = "\t";
echo "Pr0001 \t Cdclie \t CodFis \t \n ";
$data = "Select t1.Pr0001, t2.CDCLIE, t1.CODFIS FROM MYLIB.ANAGR001F AS t1";
$result = db2_exec($db2, $data);
while ($row = db2_fetch_both($result)) {
$schema_insert = "";
$schema_insert .= "$row[0]".$sep;
$schema_insert .= "$row[1]".$sep;
$schema_insert .= "$row[2]".$sep;
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
print(trim(str_replace(',', " ", $schema_insert)));
print "\n";
}
file_put_contents('test.xls', $schema_insert);
$to = "yanez25#libero.it";
$from = "robert_tr13#libero.it";
$subject = "test mail";
$separator = md5(date('r', time()));
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "test.xls";
$attachment = chunk_split(base64_encode(file_get_contents('test.xls')));
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
$body = "--".$separator.$eol;
$headers .= "Content-type:text/plain; charset=iso-8859-1".$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment; filename=\"".$filename."\"".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
if (mail($to, $subject, $body, $headers)) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR";
}
?>

There is no need to reinvent the wheel when you have robust PHP libraries that do this for you.
Using PHPMailer which is one of the popular. You can send string attachment by adding it like so:
$mail->AddStringAttachment($attachment,$filename,$encoding,$type);
$encoding and $type are optional
You can check here for the full configuration and settings and if you feel you need to be part of the invention, you can either contribute code or funding.

Related

create .xls file and send it in mail using php

My code to create xls file & attach it into mail is below:
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=test.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
echo "Name \t Email \t Phone \t \n ";
while($row = mysqli_fetch_array($result,MYSQLI_BOTH)){
$schema_insert = "";
$schema_insert .= "$row[0]".$sep;
$schema_insert .= "$row[1]".$sep;
$schema_insert .= "$row[2]".$sep;
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim(str_replace(',', " ", $schema_insert)));
print "\n";
}
file_put_contents('test.xls', $schema_insert);
$to = "ex#example.com";
$from = "ex#example.com";
$subject = "test mail";
$separator = md5(date('r', time()));
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "test.xls";
//$pdfdoc is PDF generated by FPDF
$attachment = chunk_split(base64_encode(file_get_contents('test.xls')));
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
// no more headers after this, we start the body! //
$body = "--".$separator.$eol;
$header .= "Content-type:text/plain; charset=iso-8859-1".$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment; filename=\"".$filename."\"".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
if (mail($to, $subject, $body, $headers)) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR";
}
It create .xls file and mail attachment work perfect. This all thing is happen when I click on submit button.
My problem is when I click on submit button this .xls file get download. This should not happen. & The column name in .xls file echo "Name \t Email \t Phone \t \n "; is display only in that .xls file which was download on submit button click. But the .xls file that send into mail is contain only ROW data, No column name.
Can anyone suggest what is mistake in my code? And last thing, this .xls file should downloadable from mail. But I am only able to view it in new tab. No Preview, Not able to download.
Any help would be appreciated. Thanks.
i) Remove the header code to avoid download when click a button.
ii) Change the fieldname code as below,
$schema_insert = "Name \t Email \t Phone \t \n ";

PHP mail with attachment

Hello i'm trying to send email from form^) Here is my code
<?php
$to = "some email";
$from = "site";
$subject = "Resume";
$boundary = "---";
if (isset($_POST['ok'])){
$filename = $_POST['fileField'];
$resumeLink = $_POST['linkField'];
$message = "Attachment: " .$resumeLink;
/* Headers*/
$headers = "From: $from\nReply-To: $from\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";
$body = "--$boundary\n";
/* Add message */
$body .= "Content-type: text/html; charset='utf-8'\n";
$body .= "Content-Transfer-Encoding: quoted-printablenn";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($filename)."?=\n\n";
$body .= $message."\n";
$body .= "--$boundary\n";
$file = fopen($filename, "r"); //open file
$text = fread($file, filesize($filename)); //read file
fclose($file); //close file
/* Add message type */
$body .= "Content-Type: application/octet-stream; name==?utf-8?B?".base64_encode($filename)."?=\n";
$body .= "Content-Transfer-Encoding: base64\n";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($filename)."?=\n\n";
$body .= chunk_split(base64_encode($text))."\n";
$body .= "--".$boundary ."--\n";
if(mail($to, $subject, $body, $headers)){header("Location: /");}
}
?>
Attachment will send, but it size will be 1 byte without any content inside. Whats wrong?
It's hard to tell exactly, but you've added header fields into mail body, you should add them in headers

How save a PDF file above public root and then retrieve it in PHP? (using fpdf)

I'm using fpdf to output a file to the server and then trigger an email. This works but there will be sensitive information in the pdf. How do I output the pdf to a folder above the public root? And then how do I retrieve that file again through a link?
<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output('/applications/doc.pdf','F');
?>
<?php
$to = "oelbaga#newworldgroup.com";
$from = "Omar <oelbaga#newworldgroup.com>";
$subject = "Test Attachment Email";
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "doc.pdf";
//$pdfdoc is PDF generated by FPDF
$attachment = chunk_split(base64_encode($pdf));
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
// no more headers after this, we start the body! //
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
// send message
if (mail($to, $subject, $body, $headers)) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR";
}
?>
Got it, although there are probably major security holes with this.
Code to output the fpdf file above the public webroot:
$pdf->Output('...physical..path.../doc.pdf','F');
Retrieve that pdf and force a download:
$oefilename = "doc.pdf";
$rootDir = realpath('/var/www/vhosts/lavaansmile.com/private/');
$fullPath = realpath($rootDir . '/' . $oefilename);
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename=' . basename($fullPath));
header('Content-Length: ' . filesize($fullPath));
#readfile($fullPath);
To get the physical path to your page you can use this:
//get real path
$path = 'NameofYourPage.php';
echo realpath($path);

HTML Email mixed (html & attachement) coming thoough as plain text

I've got an HTML email being sent by PHP, with a pdf attached via base64 encoding. It all works, except the email comes through as plain text, so you see all HTML tags and base64 output - obviously not ideal. There must be something I'm missing here to ensure it gets read as HTML & attachment.
If anybody can help that would be fantastic!
My PHP:
<?php $to = $email;
$message = 'testing...';
$subject = 'Health Insurance Quote Request';
$headers = "From: Andy - CEO Health.com.au <" . strip_tags('info#health.com.au') . ">\r\n";
$headers .= "Reply-To: Andy - CEO Health.com.au <". strip_tags('info#health.com.au') . ">\r\n";
// 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
$email_message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$email_message .= "--{$mime_boundary}\n";
//get PDF URL
$data = chunk_split(base64_encode(file_get_contents('http://example.com/doge.pdf')));
$email_message .= "Content-Type: {\"application/pdf\"};\n" . " name=\"$product\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$product\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$email_message .= "--{$mime_boundary}\n";
mail($email, $subject, $email_message, $headers);
Example of output:
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="==Multipart_Boundary_xc9c6c260d1e99ba11f86b40c6c7848e0x"
This is a multi-part message in MIME format.
--==Multipart_Boundary_xc9c6c260d1e99ba11f86b40c6c7848e0x
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
testing...
--==Multipart_Boundary_xc9c6c260d1e99ba11f86b40c6c7848e0x
Content-Type: {"application/pdf"};
name="HeartPlus65"
Content-Disposition: attachment;
filename="HeartPlus65"
cwt/SGdVm9X6LXQwvq03c+afGdAA9NlSAk1G3NyG2S5pDSY+CycXKDnuBJ5gFRupvZva0H2CXQqA
t9M6DlWx646bhhsx8NXdde0ES4z+8FP03XNEWTPMc/lWObbIG4ET4qxQ57eCm1V8RZOOzqG6+pu7
mYERMqHobI26KpfZYx27x8ESi65xkqOYkdbFIJ1qm2HXUEGZC0B1Jr2c6qmHeo3VULGurdIKhERP
Q6EJqtQ6rrWPbLiqzHgOlVLrfaIU8Zxe2SUhi4QTauK9G0/qbmjb2TD0HNkakoNlLbDzCql32d4A
khPjiE9rBQZGOvRvtxnEaGAlXimw7Vp4tIsqkjkI2JQ1upHBRgTA31CjqPNBjdM9ISRKHl9MLvc0
LeZUH8J7GNA1R+8mJvqkR0p5f7LZEbSkt7c2fopKX79LsEe2O7nv6qzJrc1xGreCsS
....
It may be not having a -- at the end of the last boundary tag
ie $email_message .= "--{$mime_boundary}\n";
to $email_message .= "--{$mime_boundary}--\n";
I'm not sure it there is a difference between multipart/mixed and multipart/alternative but this works for me
# Setup mime boundary
$mime_boundary = 'Multipart_Boundary_x'.md5(time()).'x';
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
$headers .= "Content-Transfer-Encoding: 7bit\n";
$body = "This is a multi-part message in mime format.\n\n";
# Add in plain text version
$body .= "--$mime_boundary\n";
$body .= "Content-Type: text/plain; charset=\"charset=us-ascii\"\n";
$body .= "Content-Transfer-Encoding: 7bit\n\n";
$body .= $text_content;
$body .= "\n\n";
# Add in HTML version
$body .= "--$mime_boundary\n";
$body .= "Content-Type: text/html; charset=\"UTF-8\"\n";
$body .= "Content-Transfer-Encoding: 7bit\n\n";
$body .= $html_content;
$body .= "\n\n";
#Attachments
if ($path!='' && $filename!=''){
$file_size = filesize($path.$filename);
$handle = fopen($path.$filename, "r");
$filecontent = fread($handle, $file_size);
fclose($handle);
$filecontent = chunk_split(base64_encode($filecontent));
$body .= "--$mime_boundary\n";
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$body .= $filecontent."\r\n\r\n";
}
# End email
$body .= "--$mime_boundary--\n";

PHP: Sending mail with attach

With this code:
$Message = 'TEXT';
$boundary = "---";
$headers = "From: $from\nX-Mailer: Carline Server www.carline.ru";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";
$body = "--$boundary\n";
$body .= "Content-type: text/html; charset='utf-8'\n";
$body .= "Content-Transfer-Encoding: quoted-printable\n\n";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($_FILES['photo1']['name'])."?=\n\n";
$body .= $Message."\n";
$body .= "--$boundary\n";
$text = file_get_contents($_FILES['photo1']['tmp_name']);
$body .= "Content-Type: application/octet-stream; name==?utf-8?B?".base64_encode($_FILES['photo1']['name'])."?=\n";
$body .= "Content-Transfer-Encoding: base64\n";
$body .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode($_FILES['photo1']['name'])."?=\n\n";
$body .= chunk_split(base64_encode($text))."\n";
$body .= "--".$boundary ."--\n";
mail($AdminEmail, "RE:", $body, $headers);
It sends a file-content in the message body
Content-Type: application/octet-stream; name==?utf-8?B?MDAwMDU3ODcuanBn?=
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename==?utf-8?B?MDAwMDU3ODcuanBn?=
/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcG
BwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwM
DAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAGQAZADASIA
...
How to change this code for sending file as attachment?
From php.net # http://php.net/manual/en/function.mail.php
Send Multi attachment email
<?php
function multi_attach_mail($to, $files, $sendermail){
// email fields: to, from, subject, and so on
$from = "Files attach <".$sendermail.">";
$subject = date("d.M H:i")." F=".count($files);
$message = date("Y.m.d H:i:s")."\n".count($files)." attachments";
$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 = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
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;
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ return $i; } else { return 0; }
}
?>
An example of header construction
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
// content type: mixed or related ( better mixed for attachments
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$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";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
You should be using pre-written libraries (e.g. http://swiftmailer.org/) to send emails, esp. the ones with attachments, whether inline or not.
Constructing valid and cross-mail client supported message is considerably advance task, esp. if you have never done this before. So why spend time re-inventing a weel when someone did the job for you already?
Put this question from the other end and if you want to build your own library, analyze what's already been done in SwiftMailer and use those snippets where needed.

Categories