The way I create my Word document is this :
// 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');
The way people recommend attaching files to php mails is the following:
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();
I have a problem with the PATH_OF_YOUR_FILE_Here part, The code I use for creating the word document just serves it to the user so they download it, but what is the path to it ?
Help is really appreciated, thanks
You need to create the file on your server first in order to attach it to an email. You can delete the file from your server after sending the email.
The header()
and php://output
are telling the user's browser to download the file, so if you remove the header and change saveAs()
to be a real (writeable) path on your server, you should end up with a file that you can then attach to an email.
I'd recommend writing the file to a new location (above your server root) to store these temporary files rather than within the source code. Then ->saveAs('/path/to/file/File.docx');
and $file_to_attach = '/path/to/file/File.docx';
.