skip to Main Content

What is the correct way to generate an email attachment with PhpWord?
I tried multiple ways but I get a corrupt file with size 1kb. If I trigger a download of the file instead, the file is OK.

$fileName = 'file.docx';
$fileAttachment = tempnam(sys_get_temp_dir(), 'PHPWord');
$template->saveAs($fileAttachment);
$contentType = "application/octet-stream";

$notification
    ->setTemplate("template", $templateParams)
    ->setSubject($this->_("Email subject"))
    ->addRecipient("to", $email, $email)
    ->addAttachment($fileName, $fileAttachment, $contentType);

What am I doing wrong?
Thank you!

2

Answers


  1. You could try to use file_get_contents function to read the contents of the file and then pass it as the second parameter to the addAttachment() method:

    $fileAttachmentContent = file_get_contents($fileAttachment);
    $notification
        ->setTemplate("template", $templateParams)
        ->setSubject($this->_("Email subject"))
        ->addRecipient("to", $email, $email)
        ->addAttachment($fileName, $fileAttachmentContent, $contentType);
    
    Login or Signup to reply.
  2. PHPWord is for generating Word documents, but it does not send mails.
    You can combine it with any PHP mailer library. This is a sample on how to do it using SwitfMailer:

    <?php
    require_once '[...]/phpword/src/PhpWord/Autoloader.php';
    require_once '[...]/swiftmailer/lib/swift_required.php';
    
    // create a new document with phpWord
    $phpWord = new PhpOfficePhpWordPhpWord();
    $section = $phpWord->addSection();
    $text = $section->addText("Here your text...");
    
    // Use Swift Mailer to create an attachment object...
    $attachment = new Swift_Attachment(
        $phpWord->save(),
        'file.docx',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    );
    // ...and send the email
    $transport = Swift_SmtpTransport::newInstance('smtp.yoursmtp.com', 25);
    $mailer = Swift_Mailer::newInstance($transport);
    $message = Swift_Message::newInstance('Here your subject')
        ->setFrom(['[email protected]' => 'Sender Name'])
        ->setTo(['[email protected]' => 'Receiver Name'])
        ->setBody('Here the body message...')
        ->attach($attachment);
    $result = $mailer->send($message);
    

    You can use any other mail library you like. Or even use the PHP mail() function, but is more tricky to set the mail headers properly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search