Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phpmailer attach pdf from dynamic url

I'm sending an email using phpmailer. I have web service to generate pdf. This pdf is not uploading or downloading to anywhere.

PDF url is like

http://mywebsite/webservices/report/sales_invoice.php?company=development&sale_id=2

I need to attach this dynamic pdf url to my email. My email sending service url is like

http://mywebsite/webservices/mailservices/sales_email.php

Below is the code which i am using to attach the pdf.

$pdf_url = "../report/sales_invoice.php?company=development&sale_id=2";
$mail->AddAttachment($pdf_url);

Sending message is working but pdf doesn't attached. It gives below message.

Could not access file: ../report/sales_invoice.php?company=development&sale_id=2

I need some help

like image 689
Irawana Avatar asked Jul 16 '13 19:07

Irawana


1 Answers

To have the answer right here:

As phpmailer would not auto-fetch the remote content, you need to do it yourself.

So you go:

// we can use file_get_contents to fetch binary data from a remote location
$url = 'http://mywebsite/webservices/report/sales_invoice.php?company=development&sale_id=2';
$binary_content = file_get_contents($url);

// You should perform a check to see if the content
// was actually fetched. Use the === (strict) operator to
// check $binary_content for false.
if ($binary_content === false) {
   throw new Exception("Could not fetch remote content from: '$url'");
}

// $mail must have been created
$mail->AddStringAttachment($binary_content, "sales_invoice.pdf", $encoding = 'base64', $type = 'application/pdf');

// continue building your mail object...

Some other things to watch out for:

Depending on the server response time, your script might run into timing issues. Also, the fetched data might be pretty large and could cause php to exceed its memory allocation.

like image 145
Hendrik Avatar answered Oct 05 '22 07:10

Hendrik