在 PHP 中创建一个 word 文件并将其附加到邮件中

Creating a word file in PHP and attaching it to a mail

我创建 Word 文档的方式是这样的:

  // I use my templace that's with my files : 
    $templateProcessor = new TemplateProcessor('Template.docx');

// I fill the template values from an sql query : 
    $templateProcessor->setValue('titre', $options['titre']);
    $templateProcessor->setValue('source', $options['source']);
    $templateProcessor->setValue('auteur', $options['auteur']);
    $templateProcessor->setValue('date_pub', $options['date_pub']);
    $templateProcessor->setValue('contenu', $options['contenu']);

 // I give the user the file (I don't fully understand how this works but it does)

    header("Content-Disposition: attachment; filename=$title.docx");
    $templateProcessor->saveAs('php://output');

人们推荐的将文件附加到 php 邮件的方式如下:

  use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

我对 PATH_OF_YOUR_FILE_Here 部分有问题,我用来创建 word 文档的代码只是将它提供给用户,以便他们下载它,但是什么是它的路径吗?

非常感谢帮助,谢谢

您需要先在您的服务器上创建文件才能将其附加到电子邮件中。发送邮件后即可delete the file from your server

header()php://output 告诉用户的浏览器下载文件,所以如果你删除 header 并将 saveAs() 更改为真正的(可写的) ) 服务器上的路径,您应该最终得到一个可以附加到电子邮件的文件。

我建议将文件写入一个新位置(在您的服务器根目录之上)以存储这些临时文件,而不是在源代码中。然后 ->saveAs('/path/to/file/File.docx');$file_to_attach = '/path/to/file/File.docx';.