Search code examples
phpmailer

PHPMailer send template in body failed


I need to send a template in my mail->body, but in the mail returned, i don't have my template but '1'.

If i do an echo of my template, my template is show good :

$template = require('../../template/newsletter/template_1.php');
echo $template;

And the fail is when i try to call my template in $mail->body like this :

$mail->Body = $template;

Solution

  • You need to return a value from the template file, just requiring it isn't enough. As the docs say:

    Successful includes, unless overridden by the included file, return 1.

    Note in particular example 5 on that page:

    return.php
    <?php
    
    $var = 'PHP';
    
    return $var;
    
    ?>
    
    noreturn.php
    <?php
    
    $var = 'PHP';
    
    ?>
    
    testreturns.php
    <?php
    
    $foo = include 'return.php';
    
    echo $foo; // prints 'PHP'
    
    $bar = include 'noreturn.php';
    
    echo $bar; // prints 1
    
    ?>
    

    So make sure you have a return statement in your template file, or have it output content and capture it with output buffering. Alternatively, use a templating system that does this for you such as Smarty or Twig.