php - 我已将 HTML 转换为 PDF,但难以使用 PHPmailer 发送 PDF
问题描述
我已经设法从我的 HTML 页面生成 pdf,但无法使用 phpmailer 将 pdf 作为附件发送。请在下面查看我的代码。我错过了什么?
关键点:
- html(tractpage2.php) 可以很好地呈现为 PDF
- PHPmailer 可以工作,但它只发送不带附件的 $message。
- 问题是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.';}
?>
解决方案
您可能希望在服务器上创建文件并保存,然后将 pdf 文件的绝对路径传递给,addAttachment
或者您也可以直接附加 DomPDF 输出而不创建文件,如下所示:
$mail->addAttachment($fileupload,'application/pdf','output.pdf', false);
推荐阅读
- javascript - 为什么 JavaScript 将向量同时定义为向量和未定义?
- csv - spark如何仅推断某些特定列的类型?
- javascript - 在停止滚动 ScrollView React Native 时从 api 获取数据
- java - 在 Hazelcast jet 中,如何将 Map 对象接收到 BatchSource?
- python - 需要帮助 discord bot 命令
- node.js - 即使 json.parse 不工作也无法访问 json 数据
- c++ - 使用 CMAKE 为 C++ 设置 Neovim
- ios - Flutter 应用程序未在具有 M1 芯片的 MacBook 上运行 iPhone 13 模拟器
- python - 使用 Python 访问 AWS Redshift
- html - 我无法将徽标添加到我的网站。它占据了整个页面。请帮我