首页 > 解决方案 > 我已将 HTML 转换为 PDF,但难以使用 PHPmailer 发送 PDF

问题描述

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

关键点:

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

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
    
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';


//reference the dompdf namescape

use Dompdf\Dompdf;

//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.';}
    
   



?>

标签: phpphpmailer

解决方案


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

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

推荐阅读