How to include php in mail body

There are a few ways to include PHP code in the body of an email:

  1. Using PHP's mail() function: You can use PHP's built-in mail() function to send an email with a PHP-generated body. Here's an example:

    <?php
    $to = '[email protected]';
    $subject = 'Test email';
    $body = '<p>Hello, world!</p>';
    mail($to, $subject, $body, 'Content-Type: text/html; charset=UTF-8');
    ?>

    In this example, the $body variable contains the HTML code for the email body, which is then sent using the mail() function.

  2. Using a PHP mail library: There are several PHP mail libraries available that allow you to send emails with a PHP-generated body. For example, you can use the PHPMailer library:

    
    <?php
    require_once 'PHPMailer/PHPMailer.php';
    require_once 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer(); $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->Port = 587; $mail->SMTPAuth = true; $mail->Username = '[email protected]'; $mail->Password = 'your_password';

$to = '[email protected]'; $subject = 'Test email'; $body = '

Hello, world!

'; $mail->setFrom('[email protected]', 'Your Name'); $mail->addAddress($to); $mail->Subject = $subject; $mail->Body = $body; $mail->send(); ?>

In this example, the `$body` variable contains the HTML code for the email body, which is then sent using the PHPMailer library.

3. **Using a templating engine**: You can use a templating engine like Twig or Smarty to generate the email body as a template, and then send the email using a PHP mail library or the `mail()` function. Here's an example using Twig:
```php
<?php
  require_once 'Twig/Autoloader.php';
  Twig_Autoloader::register();

  $loader = new Twig_Loader_Filesystem(__DIR__. '/templates');
  $twig = new Twig_Environment($loader);

  $to = '[email protected]';
  $subject = 'Test email';
  $body = $twig->render('email.twig', array('name' => 'John Doe'));
  mail($to, $subject, $body, 'Content-Type: text/html; charset=UTF-8');
?>

In this example, the email.twig template contains the HTML code for the email body, which is then rendered using the Twig templating engine and sent using the mail() function.

Remember to always validate and sanitize any user-input data before sending an email to prevent security vulnerabilities.