Search code examples
phpsendgrid

How do I send dynamic data to template file using sendgrid?


Hi I'm trying to send dynamic data to an external template file using sendgrid like this:

$sendgrid = new SendGrid(getenv('SENDGRID_KEY'));
$email = new SendGrid\Email();
$message_body = file_get_contents('../templates/emails/third-party-booking.php');

$email->addTo(getenv('SENDGRID_EMAIL'))
      ->setFrom("from@email.com")
      ->setSubject("Just a subject here")
      ->setHtml($message_body);

$sendgrid->send($email);

How do I send $details to the template, thanks!


Solution

  • If $detail contains some parameters that should be used in your template, you can do it on the $message_body step.

    $sendgrid = new SendGrid(getenv('SENDGRID_KEY'));
    $email = new SendGrid\Email();
    $message_body = file_get_contents('../templates/emails/third-party-booking.php');
    // $details = ['name'=>'Jean', 'email'=>'jean@gmail.com'];
    // third-party-booking.php content be like 
    // <html>...%name%.....%email%...</html>
    
    foreach ($details as $parameter => $value) {
        $message_body= str_replace('%' . $parameter . '%', $value, $message_body);
    }
    
    $email->addTo(getenv('SENDGRID_EMAIL'))
          ->setFrom("from@email.com")
          ->setSubject("Just a subject here")
          ->setHtml($message_body);
    
    $sendgrid->send($email);
    

    There are no way to send data to a php file as it does a copy of the file content (see PHP - include a php file and also send query parameters)