繁体   English   中英

发送动态 PHP HTML With Sendgrid Web API

[英]Send Dynamic PHP HTML With Sendgrid Web API

我想使用 Sendgrid WebAPI,最好不要使用 SMTP 或使用下面的代码的 Swiftmailer。 是否可以将整个动态网页传递给“html”$params 数组而不创建长字符串变量并且需要转义每个引号并回显每个变量? 每个 email 都有很大差异,因此 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这样的模板引擎。 因此,在您的示例中,在实际发送 email 的上方某处,您可以执行以下操作:

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 正文的 email 时:

....

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM