使用 Sendgrid Web API 发送动态 PHP HTML


Send Dynamic PHP HTML With Sendgrid Web API

我想使用以下代码使用Sendgrid WebAPI,最好不使用SMTP或Swiftmailer。是否可以将整个动态网页传递给"html"$params数组,而无需创建长字符串变量并需要转义每个引号并回显每个变量?每封电子邮件差异很大,因此 Sendgrid 的模板/邮件合并选项对我不起作用。谢谢!

这是一个简单的 html 示例(我的有更多的动态内容):

<html>
  <head></head>
  <body>
    <p>Hi I'm <?php echo $name; ?>!<br>
       <span style="color: #999999; font-size: 11px;">How are you?</span><br>
    </p>
  </body>
</html>
$url = 'http://sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD'; 
$params = array(
    'api_user'  => $user,
    'api_key'   => $pass,
    'to'        => 'example3@sendgrid.com',
    'subject'   => 'testing from curl',
    'html'      => 'testing body',
    'text'      => 'testing body',
    'from'      => 'example@sendgrid.com',
  );

$request =  $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
// print everything out
print_r($response);

生成所需HTML的最佳方法是使用像Smarty这样的模板引擎。因此,在您的示例中,在实际发送电子邮件上方的某个地方,您将执行以下操作:

include('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('name', 'Swift');
$smarty->assign('name', 'SendGrid');
$smarty->assign('address', '123 Broadway');
// Store it in a variable
$emailBody = $smarty->fetch('some_dynamic_template.tpl');

然后,当您实际需要发送带有新动态HTML正文的电子邮件时:

....
$params = array(
    'api_user'  => $user,
    'api_key'   => $pass,
    'to'        => 'example3@sendgrid.com',
    'subject'   => 'testing from curl',
    'html'      => $emailBody,
    'from'      => 'example@sendgrid.com',
);
....

在同样的情况下,通过使用替换标记,SMTP API更容易,更多详细信息:http://sendgrid.com/docs/API_Reference/SMTP_API/substitution_tags.html