如何使用 sendgrid 将动态数据发送到模板文件?

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

您好,我正在尝试使用 sendgrid 将动态数据发送到外部模板文件,如下所示:

$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);

如何将$details发送到模板,谢谢!

如果 $detail 包含一些应该在您的模板中使用的参数,您可以在 $message_body 步骤中进行。

$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);

无法将数据发送到 php 文件,因为它会复制文件内容(参见 PHP - include a php file and also send query parameters