我已经将HTML转换为PDF,但很难使用PHPmailer发送PDF



>我已经设法从我的HTML页面生成pdf,但无法使用phpmailer将pdf作为附件发送。请参阅下面的代码。我错过了什么?

要点:

  1. html(tractpage2.php(可以很好地呈现为PDF
  2. PHPmailer可以工作,但它只发送没有附件的$message。
  3. 问题是 pdf 没有附加邮件

<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';
//reference the dompdf namescape
use DompdfDompdf;
//initialise dompdf class
// get/setup the htmlpage
ob_start();
require("tractpage2.php"); // The html document
$page = ob_get_contents();
ob_end_clean();
// convert to pdf
$document = new Dompdf();
$document->set_option('defaultFont', 'Courier');
$document->load_html($page);
// set paper orientation
$document->set_paper('A4', 'portrait');
// Render the HTML as PDF
$document->render();
// Output the generated PDF to Browser
$document->stream("contract.pdf", array("Attachment"=>0));
//1 = download
//0= preview
$fileupload = $document->output();
// setup email 
$message = "Am new to programming and loving it";
$mail = new PHPMailer;                             
//Server settings
$mail->SMTPDebug = 2;                                 // Enable verbose debug output
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'xxxx@gmail.com';                 // SMTP username
$mail->Password = 'xxxxxx';                           // SMTP password
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;                                    // TCP port to connect to
//Recipients
$mail->setFrom('xxxxx@gmail.com', 'james');
$mail->addAddress('xxxx@aol.com', 'name of receiver');     // Add a recipient
$mail->addAddress('xxxxx@yahoo.com');               // Name is optional

//Attachments
$mail->addAttachment($fileupload);         // Add attachments


//Content
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = $message;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if ($mail->send()){
echo 'Message has been sent';}
else { echo 'Message could not be sent.';}


?>

您可能希望在服务器上创建文件并保存,然后将pdf文件的绝对路径传递给addAttachment或者您也可以直接附加DomPDF输出而无需创建文件,如下所示:

$mail->addAttachment($fileupload,'application/pdf','output.pdf', false);

最新更新