如何使用 SendGrid 发送电子邮件

How to send email using SendGrid

我一直在尝试使用 SendGrid 的 PHP API 为网页设置电子邮件,但我没有成功。我尝试了 Azure 网站上的代码以及我在尝试 Google 时发现的各种示例,但每次它 returns 都没有响应,并且未设置电子邮件。这是我正在谈论的代码:

<?php
 $url = 'https://api.sendgrid.com/';
 $user = 'USERNAME';
 $pass = 'PASSWORD'; 

 $params = array(
      'api_user' => $user,
      'api_key' => $pass,
      'to' => 'email@gmail.com',
      'subject' => 'testing from curl',
      'html' => 'testing body',
      'text' => 'testing body',
      'from' => 'anna@contoso.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);
 ?>

同样值得注意的是,我曾尝试使用 sendgrid-php 以及随附的代码,这导致页面根本无法加载。我现在真的很困惑,非常感谢任何帮助。

您的 cURL 版本可能不立即支持 SSL。

您可以通过将以下内容放在代码顶部来测试它:

if (!curl_version()['features'] & CURL_VERSION_SSL) {
    echo "SSL is not supported with this cURL installation.";
}

如果不支持开箱即用,您必须像这样手动配置它:

curl_setopt($session, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYHOST, 2);
// path to CA certificate
curl_setopt($session, CURLOPT_CAINFO, '/etc/openssl/cert.pem'); 

默认情况下,Azure 不会为 Azure Web 应用程序生成 SSL 对等证书。如果您在测试代码中添加代码 $error = curl_error($session);,您将收到错误 SSL certificate problem: self signed certificate in certificate chain.

您只需添加代码curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0);即可绕过验证。

否则,您可以按照Verify Peer Certificate from PHP cURL for Azure Apps在Azure Web Apps上添加证书。