Search code examples
phpphpmailer

How can I add an expression inside the $mail-> Body in phpMailer?


The phone number in a form isn't required. I would like to hide the label if the phone number field didn't collect any data.

Something like this in theory?

$mail->Body = "
  <p><strong>Name: </strong> $full_name</p> 
  <p><strong>Email: </strong> $email</p>". 
  if ($phone !== ''){
    echo '<p><strong>Phone: </strong> $phone</p>';
  } else {
    echo '';
  } . "
  <p><strong>Message: </strong> $message</p> 
";

But is not the right syntax. How can I do this? p.s. a Ternary expression would even be cleaner, but it didn't work either


Solution

  • Don't echo, append content:

    $mail->Body = "<p><strong>Name: </strong> $full_name</p> 
      <p><strong>Email: </strong> $email</p>";
     
      if ($phone !== ''){
        $mail->Body .= '<p><strong>Phone: </strong> $phone</p>';
      }
    
      $mail->Body .= '<p><strong>Message: </strong> $message</p>';