I am getting dynamic content on page load and sending it via mail using wp_mail(). Right now all contents going in body section of email but I want it to store in .doc(MS word) file and then send that file as an attachment.

I can send attachment via wp_mail(). But I am not getting any solution about how to auto create file and store all html content in file. I search a lot on google but couldn't find anything helpful. Is there any possible way of doing this in wordpress?


Can't help you with the creation of the .doc-file, as i have never done that. But if you manage to get the encoded file into a string, you can work with the Wordpress PHP-Mailer instance like this:

function send_my_mail_with_attachment($from,$to,$subject,$body,$attachmentstring=""){
        global $phpmailer;
        // (Re)create it, if it's gone missing
        if ( ! ( $phpmailer instanceof PHPMailer ) ) {
            require_once ABSPATH . WPINC . '/class-phpmailer.php';
            require_once ABSPATH . WPINC . '/class-smtp.php';
            $phpmailer = new PHPMailer( true );
        $phpmailer->CharSet = 'UTF-8';
        $phpmailer->Sender = $phpmailer->From;
        $phpmailer->isHTML(true);   // Set email format to HTML
        $phpmailer->Subject = $subject;
        $phpmailer->Body    = $body;
        $rueckgabe = $phpmailer->Send(); 
        return $rueckgabe;

You can learn more about PHPMailer here

| improve this answer | |
  • If it can be done with pdf then also its fine. – Rishabh Jan 10 '18 at 9:23
  • 1
    Yep. Actually, i modified this code as it previous worked with pdf. You can use mpdf, which is a fork of fpdf, also. You get the String for the string-attachment like this: $attachmentstring = $mpdf->Output('my_temp_file.pdf', 'S'); (You of course have to change the function to $phpmailer->AddStringAttachment($attachmentstring,'my_attachment.pdf'); ) – HU ist Sebastian Jan 10 '18 at 9:28

If a document is meant to open on someone else's computer it's always a good practice to send it in a PDF format, that way you can maintain the styling and font of the document.

If you agree, you can use FPDF to create PDF files with dynamic content.

here is a code example:

$pdf = new FPDF();
$pdf->Rect(10, 10, 190, 135, 'D');
$pdf->Cell(30,10,'Document Title');
$op = $pdf->Output();

you can generate and save the pdf on your server and then use the method suggested by @kuchenundkakao to attach it to the email.

| improve this answer | |
  • "If you agree" Yes, no issues if it will be pdf instead of doc file :) – Rishabh Jan 10 '18 at 9:22
  • cool. let me know if it worked for you. – Sid Jan 10 '18 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.