Search code examples
phppdfattachmentmail-mime

php Mail_MIME - Generating and Attaching PDF


I am trying to write a PHP script that will generate a PDF and email it. My PDF generator works perfectly as an independent URL, but for some reason when I try to make the script email the generated PFD, the received file can't be opened. Here is the code:

include_once('Mail.php');
include_once('Mail/mime.php');

$attachment = "cache/form.pdf";

// vvv This line seems to be where the breakdowns is vvv
file_put_contents( $attachment, file_get_contents( "http://www.mydomain.com/generator.php?arg1=$arg1&arg2=$arg2" ) );

$message = new Mail_mime();
$message->setTXTBody( $msg );
$message->setHTMLBody( "<html><body>$msg</body></html>" );
$message->addAttachment( $attachment );
$body = $message->get();

$extraheaders = array(  "From"      => $from,
            "Cc"        => $cc,
            "Subject"   => $sbj );

$mail = Mail::factory("mail");

$headers = $message->headers( $extraheaders );
$to = array(    "Jon Doe <jon@mydomain.com>",
        "Jane Doe <jane@mydomain.com>" );
$addresses = implode( ",", $to );

if( $mail->send($addresses, $headers, $body) )
    echo    "<p class=\"success\">Successfully Sent</p>";
else
    echo    "<p class=\"error\">Message Failed</p>";

unlink( $attachment );

The line that I marked does generate a PDF file in the cache folder, but it will not open, so that seems to be a problem. However, when I try to attach a PDF file already exists, I have the same problem. I have tried $message->addAttachment( $attachment, "Application/pdf" ); as well, and it does not seem to make a difference.


Solution

  • I am pretty sure it must be an ini problem blocking file_get_contents(). However I came up with a better solution. I reworked the generator.php file and turned it in to a function definition. So I've got:

    include_once('generator.php');
    $attachment = "cache/form.pdf";
    file_put_contents( $attachment, my_pdf_generator( $arg1, $arg2 ) );
    ...
    $message->addAttachment( $attachment, "application/pdf" );
    

    This way I do not need to write the file first. It works great (although I am still having slight issues with Outlook/Exchange Server, but I think that is a largely unrelated issue).