我正在尝试编写一个PHP脚本,它将生成PDF并通过电子邮件发送给它。我的PDF生成器完美地作为一个独立的URL工作,但由于某些原因,当我尝试使脚本通过电子邮件发送生成的PFD时,无法打开收到的文件。这是代码:
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 );
我标记的行确实在缓存文件夹中生成PDF文件,但它不会打开,因此这似乎是个问题。但是,当我尝试附加已存在的PDF文件时,我遇到了同样的问题。我也尝试了$message->addAttachment( $attachment, "Application/pdf" );
,但它似乎没有什么区别。
答案 0 :(得分:1)
通常,Web服务器目录应锁定写入权限。这可能是您遇到file_put_contents('cache/form.pdf')
问题的原因。
// A working example: you should be able to cut and paste,
// assuming you are on linux.
$attachment = "/var/tmp/Magick++_tutorial.pdf";
file_put_contents($attachment, file_get_contents(
"http://www.imagemagick.org/Magick++/tutorial/Magick++_tutorial.pdf"));
尝试将pdf保存的位置更改为允许每个人具有写入和读取权限的目录。还要确保此目录不在您的Web服务器上。
还尝试更改以下三件事
这
$message = new Mail_mime();
要
// you probably don't need this the default is
// $params['eol'] - Type of line end. Default is ""\r\n""
$message = new Mail_mime("\r\n");
来自
$extraheaders = array(
"From" => $from,
"Cc" => $cc,
"Subject" => $sbj,
);
要
$extraheaders = array(
"From" => $from,
"Cc" => $cc,
"Subject" => $sbj,
'Content-Type' => 'text/html'
);
这
$message->addAttachment($attachment);
要
// the default second argument is $c_type = 'application/octet-stream'
$isAttached = $message->addAttachment($attachment, 'aplication/pdf');
if ($isAttached !== true) {
// an error occured
echo $isAttached->getMessage();
}
你总是想确保你打电话
$message->get();
之前
$message->headers($extraheaders);
或整件事不会工作
答案 1 :(得分:0)
我很确定它必须是阻止file_get_contents()的ini问题。但是我想出了一个更好的解决方案。我重新编写了generator.php文件并将其转换为函数定义。所以我得到了:
include_once('generator.php');
$attachment = "cache/form.pdf";
file_put_contents( $attachment, my_pdf_generator( $arg1, $arg2 ) );
...
$message->addAttachment( $attachment, "application/pdf" );
这样我就不需要先写文件了。它运行良好(虽然我仍然遇到Outlook / Exchange Server的轻微问题,但我认为这是一个很大程度上无关的问题。)