0

I want to form a file (PHPExcel) and mail it as an attachment (PHPMailer) without server storing, is it possible?

I'm aware of the possibility of forming/creating file in PHPExcel and sending it as an attachment thru PHPMailer here. But it works thru/by writing a file somewhere in a server. Poor as far as server resources consumption. PHPExcel allows to output this way directly without saving on a server:

$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
ob_end_clean(); 
header('Content-Type: application/vnd.ms-excel');
...
$objWriter->save('php://output'); 

Is it possible (and how) to attach it to email on the fly similar as save('php://output')?

Community
  • 1
  • 1
Igor Savinkin
  • 5,669
  • 8
  • 37
  • 69
  • 1
    http://stackoverflow.com/questions/11164167/phpmailer-attachment-doing-it-without-a-physical-file capture excel output to string, use linked method to attach to email. but be aware that if your excel gets "large", you could easily kill your script with an out-of-memory error. – Marc B Nov 26 '14 at 14:58
  • @MarcB, thank you for a warning, but if Excel file is of 3M size, would't it be overload and out-of-memory error? – Igor Savinkin Nov 26 '14 at 15:13
  • no idea. that depends on what you've set your php memory limit. but consider that you're going to have the captured string copied a few times: original capture, passing to phpmailer for attachment, and then embedded again in the email as it's built. – Marc B Nov 26 '14 at 15:15
  • 1
    Just get your data into a string, and pass it to `addStringAttachment` on your PHPMailer instance. – Synchro Nov 26 '14 at 15:35
  • @Synchro, i've done it. You might make it an answer and i'll check it. – Igor Savinkin Dec 25 '14 at 14:10

1 Answers1

1

To send an attachment without using local files, use the addStringAttachment() method. For example:

$string = $mything->getExcelData();
$mail->addStringAttachment($string, 'myfile.xls');

Internally this will call PHPMailer::filenameToType(), which will set the appropriate application/vnd.ms-excel MIME type for the .xls extension.

In general you probably don't need to worry too much about memory consumption for doing this - PHPExcel itself is far more memory-intensive than simply storing this string temporarily, so if you are running into trouble, you will likely do so before you ever get this far

Synchro
  • 35,538
  • 15
  • 81
  • 104