如何使用SendGrid发送电子邮件

时间:2016-10-18 21:13:19

标签: php azure sendgrid

我一直在尝试使用SendGrid的PHP API为网页设置电子邮件,而且我没有运气。我已经尝试了Azure网站上的代码以及我在尝试Google时发现的各种示例,并且每次都没有返回任何响应,并且电子邮件没有设置。这是我正在谈论的代码:

<?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并附带随其提供的代码,这导致页面无法加载。我现在真的很难过,非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

默认情况下,Azure不会为Azure Web Apps生成SSL对等证书。如果您在测试代码@IBAction func shareMeme(_ sender: AnyObject) { let img: UIImage = generateMemedImage() let shareItems:Array = [img] let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil) self.save() print("Saved") activityViewController.completionWithItemsHandler = {(activityType, completed:Bool, returnedItems:[AnyObject]?, error: NSError?) in self.save() print("Saved") } self.present(activityViewController, animated: true, completion: nil) } 中添加代码,则会收到错误$error = curl_error($session);

您只需添加代码SSL certificate problem: self signed certificate in certificate chain即可绕过验证。

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

答案 1 :(得分:0)

您的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');